[multiple changes]
[gcc.git] / gcc / ada / sem_ch3.adb
index f4983035fd109ae97999387942c6b716b2a7239a..65c85762ef7177be74dc5bee2adb6858845e1baf 100644 (file)
@@ -6,7 +6,7 @@
 --                                                                          --
 --                                 B o d y                                  --
 --                                                                          --
---          Copyright (C) 1992-2014, Free Software Foundation, Inc.         --
+--          Copyright (C) 1992-2015, Free Software Foundation, Inc.         --
 --                                                                          --
 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
 -- terms of the  GNU General Public License as published  by the Free Soft- --
@@ -39,6 +39,7 @@ with Exp_Tss;  use Exp_Tss;
 with Exp_Util; use Exp_Util;
 with Fname;    use Fname;
 with Freeze;   use Freeze;
+with Ghost;    use Ghost;
 with Itypes;   use Itypes;
 with Layout;   use Layout;
 with Lib;      use Lib;
@@ -57,6 +58,7 @@ with Sem_Ch6;  use Sem_Ch6;
 with Sem_Ch7;  use Sem_Ch7;
 with Sem_Ch8;  use Sem_Ch8;
 with Sem_Ch10; use Sem_Ch10;
+with Sem_Ch12; use Sem_Ch12;
 with Sem_Ch13; use Sem_Ch13;
 with Sem_Dim;  use Sem_Dim;
 with Sem_Disp; use Sem_Disp;
@@ -92,8 +94,8 @@ package body Sem_Ch3 is
    --  record type.
 
    procedure Analyze_Object_Contract (Obj_Id : Entity_Id);
-   --  Analyze all delayed aspects chained on the contract of object Obj_Id as
-   --  if they appeared at the end of the declarative region. The aspects to be
+   --  Analyze all delayed pragmas chained on the contract of object Obj_Id as
+   --  if they appeared at the end of the declarative region. The pragmas to be
    --  considered are:
    --    Async_Readers
    --    Async_Writers
@@ -532,8 +534,8 @@ package body Sem_Ch3 is
    function Find_Type_Of_Object
      (Obj_Def     : Node_Id;
       Related_Nod : Node_Id) return Entity_Id;
-   --  Get type entity for object referenced by Obj_Def, attaching the
-   --  implicit types generated to Related_Nod
+   --  Get type entity for object referenced by Obj_Def, attaching the implicit
+   --  types generated to Related_Nod.
 
    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id);
    --  Create a new float and apply the constraint to obtain subtype of it
@@ -590,6 +592,12 @@ package body Sem_Ch3 is
    --  Propagate static and dynamic predicate flags from a parent to the
    --  subtype in a subtype declaration with and without constraints.
 
+   function Is_EVF_Procedure (Subp : Entity_Id) return Boolean;
+   --  Subsidiary to Check_Abstract_Overriding and Derive_Subprogram.
+   --  Determine whether subprogram Subp is a procedure subject to pragma
+   --  Extensions_Visible with value False and has at least one controlling
+   --  parameter of mode OUT.
+
    function Is_Valid_Constraint_Kind
      (T_Kind          : Type_Kind;
       Constraint_Kind : Node_Kind) return Boolean;
@@ -650,6 +658,17 @@ package body Sem_Ch3 is
    --  present. If errors are found, error messages are posted, and the
    --  Real_Range_Specification of Def is reset to Empty.
 
+   procedure Propagate_Default_Init_Cond_Attributes
+     (From_Typ             : Entity_Id;
+      To_Typ               : Entity_Id;
+      Parent_To_Derivation : Boolean := False;
+      Private_To_Full_View : Boolean := False);
+   --  Subsidiary to routines Build_Derived_Type and Process_Full_View. Inherit
+   --  all attributes related to pragma Default_Initial_Condition from From_Typ
+   --  to To_Typ. Flag Parent_To_Derivation should be set when the context is
+   --  the creation of a derived type. Flag Private_To_Full_View should be set
+   --  when processing both views of a private type.
+
    procedure Record_Type_Declaration
      (T    : Entity_Id;
       N    : Node_Id;
@@ -730,7 +749,7 @@ package body Sem_Ch3 is
       Enclosing_Prot_Type : Entity_Id := Empty;
 
    begin
-      Check_SPARK_Restriction ("access type is not allowed", N);
+      Check_SPARK_05_Restriction ("access type is not allowed", N);
 
       if Is_Entry (Current_Scope)
         and then Is_Task_Type (Etype (Scope (Current_Scope)))
@@ -860,7 +879,14 @@ package body Sem_Ch3 is
          --  create a reference to it after the enclosing protected definition
          --  because the itype will be used in the subsequent bodies.
 
-         if Ekind (Current_Scope) = E_Protected_Type then
+         --  If the anonymous access itself is protected, a full type
+         --  declaratiton will be created for it, so that the equivalent
+         --  record type can be constructed. For further details, see
+         --  Replace_Anonymous_Access_To_Protected-Subprogram.
+
+         if Ekind (Current_Scope) = E_Protected_Type
+           and then not Protected_Present (Access_To_Subprogram_Definition (N))
+         then
             Build_Itype_Reference (Anon_Type, Parent (Current_Scope));
          end if;
 
@@ -1053,7 +1079,7 @@ package body Sem_Ch3 is
    --  Start of processing for Access_Subprogram_Declaration
 
    begin
-      Check_SPARK_Restriction ("access type is not allowed", T_Def);
+      Check_SPARK_05_Restriction ("access type is not allowed", T_Def);
 
       --  Associate the Itype node with the inner full-type declaration or
       --  subprogram spec or entry body. This is required to handle nested
@@ -1135,7 +1161,7 @@ package body Sem_Ch3 is
                if Is_Access_Type (Typ)
                  and then Null_Exclusion_In_Return_Present (T_Def)
                then
-                  Set_Etype  (Desig_Type,
+                  Set_Etype (Desig_Type,
                     Create_Null_Excluding_Itype
                       (T           => Typ,
                        Related_Nod => T_Def,
@@ -1322,7 +1348,7 @@ package body Sem_Ch3 is
       Full_Desig : Entity_Id;
 
    begin
-      Check_SPARK_Restriction ("access type is not allowed", Def);
+      Check_SPARK_05_Restriction ("access type is not allowed", Def);
 
       --  Check for permissible use of incomplete type
 
@@ -1734,22 +1760,26 @@ package body Sem_Ch3 is
                   Set_Etype (New_Subp, Etype (Iface_Prim));
                end if;
 
-               --  Internal entities associated with interface types are
-               --  only registered in the list of primitives of the tagged
-               --  type. They are only used to fill the contents of the
-               --  secondary dispatch tables. Therefore they are not needed
-               --  in the homonym chains.
+               --  Internal entities associated with interface types are only
+               --  registered in the list of primitives of the tagged type.
+               --  They are only used to fill the contents of the secondary
+               --  dispatch tables. Therefore they are not needed in the
+               --  homonym chains.
 
                Remove_Homonym (New_Subp);
 
                --  Hidden entities associated with interfaces must have set
-               --  the Has_Delay_Freeze attribute to ensure that, in case of
-               --  locally defined tagged types (or compiling with static
+               --  the Has_Delay_Freeze attribute to ensure that, in case
+               --  of locally defined tagged types (or compiling with static
                --  dispatch tables generation disabled) the corresponding
-               --  entry of the secondary dispatch table is filled when
-               --  such an entity is frozen.
+               --  entry of the secondary dispatch table is filled when such
+               --  an entity is frozen. This is an expansion activity that must
+               --  be suppressed for ASIS because it leads to gigi elaboration
+               --  issues in annotate mode.
 
-               Set_Has_Delayed_Freeze (New_Subp);
+               if not ASIS_Mode then
+                  Set_Has_Delayed_Freeze (New_Subp);
+               end if;
             end if;
 
             <<Continue>>
@@ -1769,9 +1799,10 @@ package body Sem_Ch3 is
    -----------------------------------
 
    procedure Analyze_Component_Declaration (N : Node_Id) is
-      Id  : constant Entity_Id := Defining_Identifier (N);
-      E   : constant Node_Id   := Expression (N);
-      Typ : constant Node_Id   :=
+      Loc : constant Source_Ptr := Sloc (Component_Definition (N));
+      Id  : constant Entity_Id  := Defining_Identifier (N);
+      E   : constant Node_Id    := Expression (N);
+      Typ : constant Node_Id    :=
               Subtype_Indication (Component_Definition (N));
       T   : Entity_Id;
       P   : Entity_Id;
@@ -1884,7 +1915,7 @@ package body Sem_Ch3 is
                 (Subtype_Indication (Component_Definition (N)), N);
 
          if not Nkind_In (Typ, N_Identifier, N_Expanded_Name) then
-            Check_SPARK_Restriction ("subtype mark required", Typ);
+            Check_SPARK_05_Restriction ("subtype mark required", Typ);
          end if;
 
       --  Ada 2005 (AI-230): Access Definition case
@@ -1937,8 +1968,8 @@ package body Sem_Ch3 is
       --  package Sem).
 
       if Present (E) then
-         Check_SPARK_Restriction ("default expression is not allowed", E);
-         Preanalyze_Spec_Expression (E, T);
+         Check_SPARK_05_Restriction ("default expression is not allowed", E);
+         Preanalyze_Default_Expression (E, T);
          Check_Initialization (T, E);
 
          if Ada_Version >= Ada_2005
@@ -2098,6 +2129,31 @@ package body Sem_Ch3 is
          end if;
       end if;
 
+      --  If the component is an unconstrained task or protected type with
+      --  discriminants, the component and the enclosing record are limited
+      --  and the component is constrained by its default values. Compute
+      --  its actual subtype, else it may be allocated the maximum size by
+      --  the backend, and possibly overflow.
+
+      if Is_Concurrent_Type (T)
+        and then not Is_Constrained (T)
+        and then Has_Discriminants (T)
+        and then not Has_Discriminants (Current_Scope)
+      then
+         declare
+            Act_T : constant Entity_Id := Build_Default_Subtype (T, N);
+
+         begin
+            Set_Etype (Id, Act_T);
+
+            --  Rewrite component definition to use the constrained subtype
+
+            Rewrite (Component_Definition (N),
+              Make_Component_Definition (Loc,
+                Subtype_Indication => New_Occurrence_Of (Act_T, Loc)));
+         end;
+      end if;
+
       Set_Original_Record_Component (Id, Id);
 
       if Has_Aspects (N) then
@@ -2156,10 +2212,7 @@ package body Sem_Ch3 is
                        Parameter_Specifications (Body_Spec);
          Spec      : Node_Id;
          Spec_Id   : Entity_Id;
-
-         Dummy : Entity_Id;
-         --  A dummy variable used to capture the unused result of subprogram
-         --  spec analysis.
+         Typ       : Node_Id;
 
       begin
          --  Consider only procedure bodies whose name matches one of the three
@@ -2172,29 +2225,50 @@ package body Sem_Ch3 is
          then
             return;
 
-         --  A controlled primitive must have exactly one formal
+         --  A controlled primitive must have exactly one formal which is not
+         --  an anonymous access type.
 
          elsif List_Length (Params) /= 1 then
             return;
          end if;
 
-         Dummy := Analyze_Subprogram_Specification (Body_Spec);
+         Typ := Parameter_Type (First (Params));
 
-         --  The type of the formal must be derived from [Limited_]Controlled
-
-         if not Is_Controlled (Etype (Defining_Entity (First (Params)))) then
+         if Nkind (Typ) = N_Access_Definition then
             return;
          end if;
 
-         Spec_Id := Find_Corresponding_Spec (Body_Decl, Post_Error => False);
+         Find_Type (Typ);
 
-         --  The body has a matching spec, therefore it cannot be a late
-         --  primitive.
+         --  The type of the formal must be derived from [Limited_]Controlled
 
-         if Present (Spec_Id) then
+         if not Is_Controlled (Entity (Typ)) then
             return;
          end if;
 
+         --  Check whether a specification exists for this body. We do not
+         --  analyze the spec of the body in full, because it will be analyzed
+         --  again when the body is properly analyzed, and we cannot create
+         --  duplicate entries in the formals chain. We look for an explicit
+         --  specification because the body may be an overriding operation and
+         --  an inherited spec may be present.
+
+         Spec_Id := Current_Entity (Body_Id);
+
+         while Present (Spec_Id) loop
+            if Ekind_In (Spec_Id, E_Procedure, E_Generic_Procedure)
+              and then Scope (Spec_Id) = Current_Scope
+              and then Present (First_Formal (Spec_Id))
+              and then No (Next_Formal (First_Formal (Spec_Id)))
+              and then Etype (First_Formal (Spec_Id)) = Entity (Typ)
+              and then Comes_From_Source (Spec_Id)
+            then
+               return;
+            end if;
+
+            Spec_Id := Homonym (Spec_Id);
+         end loop;
+
          --  At this point the body is known to be a late controlled primitive.
          --  Generate a matching spec and insert it before the body. Note the
          --  use of Copy_Separate_Tree - we want an entirely separate semantic
@@ -2208,8 +2282,7 @@ package body Sem_Ch3 is
          Set_Null_Present (Spec, False);
 
          Insert_Before_And_Analyze (Body_Decl,
-           Make_Subprogram_Declaration (Loc,
-             Specification => Spec));
+           Make_Subprogram_Declaration (Loc, Specification => Spec));
       end Handle_Late_Controlled_Primitive;
 
       --------------------------------
@@ -2230,17 +2303,14 @@ package body Sem_Ch3 is
 
       --  Local variables
 
-      Context     : Node_Id;
+      Context     : Node_Id   := Empty;
       Freeze_From : Entity_Id := Empty;
       Next_Decl   : Node_Id;
-      Spec_Id     : Entity_Id;
+      Pack_Decl   : Node_Id   := Empty;
 
       Body_Seen : Boolean := False;
       --  Flag set when the first body [stub] is encountered
 
-      In_Package_Body : Boolean := False;
-      --  Flag set when the current declaration list belongs to a package body
-
    --  Start of processing for Analyze_Declarations
 
    begin
@@ -2256,7 +2326,7 @@ package body Sem_Ch3 is
          if Nkind (Decl) = N_Package_Declaration
            and then Nkind (Parent (L)) = N_Package_Specification
          then
-            Check_SPARK_Restriction
+            Check_SPARK_05_Restriction
               ("package specification cannot contain a package declaration",
                Decl);
          end if;
@@ -2384,6 +2454,7 @@ package body Sem_Ch3 is
          Context := Parent (L);
 
          if Nkind (Context) = N_Package_Specification then
+            Pack_Decl := Parent (Context);
 
             --  When a package has private declarations, its contract must be
             --  analyzed at the end of the said declarations. This way both the
@@ -2393,6 +2464,15 @@ package body Sem_Ch3 is
             if L = Private_Declarations (Context) then
                Analyze_Package_Contract (Defining_Entity (Context));
 
+               --  Build the bodies of the default initial condition procedures
+               --  for all types subject to pragma Default_Initial_Condition.
+               --  From a purely Ada stand point, this is a freezing activity,
+               --  however freezing is not available under GNATprove_Mode. To
+               --  accomodate both scenarios, the bodies are build at the end
+               --  of private declaration analysis.
+
+               Build_Default_Init_Cond_Procedure_Bodies (L);
+
             --  Otherwise the contract is analyzed at the end of the visible
             --  declarations.
 
@@ -2403,43 +2483,71 @@ package body Sem_Ch3 is
             end if;
 
          elsif Nkind (Context) = N_Package_Body then
-            In_Package_Body := True;
-            Spec_Id := Corresponding_Spec (Context);
-
+            Pack_Decl := Context;
             Analyze_Package_Body_Contract (Defining_Entity (Context));
          end if;
-      end if;
 
-      --  Analyze the contracts of subprogram declarations, subprogram bodies
-      --  and variables now due to the delayed visibility requirements of their
-      --  aspects.
+         --  Analyze the contracts of all subprogram declarations, subprogram
+         --  bodies and variables now due to the delayed visibility needs of
+         --  of their aspects and pragmas. Capture global references in generic
+         --  subprograms or bodies.
 
-      Decl := First (L);
-      while Present (Decl) loop
-         if Nkind (Decl) = N_Object_Declaration then
-            Analyze_Object_Contract (Defining_Entity (Decl));
+         Decl := First (L);
+         while Present (Decl) loop
+            if Nkind (Decl) = N_Object_Declaration then
+               Analyze_Object_Contract (Defining_Entity (Decl));
 
-         elsif Nkind_In (Decl, N_Abstract_Subprogram_Declaration,
-                               N_Subprogram_Declaration)
-         then
-            Analyze_Subprogram_Contract (Defining_Entity (Decl));
+            elsif Nkind_In (Decl, N_Abstract_Subprogram_Declaration,
+                                  N_Generic_Subprogram_Declaration,
+                                  N_Subprogram_Declaration)
+            then
+               Analyze_Subprogram_Contract (Defining_Entity (Decl));
 
-         elsif Nkind (Decl) = N_Subprogram_Body then
-            Analyze_Subprogram_Body_Contract (Defining_Entity (Decl));
+            elsif Nkind (Decl) = N_Subprogram_Body then
+               Analyze_Subprogram_Body_Contract (Defining_Entity (Decl));
 
-         elsif Nkind (Decl) = N_Subprogram_Body_Stub then
-            Analyze_Subprogram_Body_Stub_Contract (Defining_Entity (Decl));
-         end if;
+            elsif Nkind (Decl) = N_Subprogram_Body_Stub then
+               Analyze_Subprogram_Body_Stub_Contract (Defining_Entity (Decl));
+            end if;
 
-         Next (Decl);
-      end loop;
+            --  Capture all global references in a generic subprogram or a body
+            --  [stub] now that the contract has been analyzed.
+
+            if Nkind_In (Decl, N_Generic_Subprogram_Declaration,
+                               N_Subprogram_Body,
+                               N_Subprogram_Body_Stub)
+              and then Is_Generic_Declaration_Or_Body (Decl)
+            then
+               Save_Global_References_In_Contract
+                 (Templ  => Original_Node (Decl),
+                  Gen_Id => Corresponding_Spec_Of (Decl));
+            end if;
+
+            Next (Decl);
+         end loop;
 
-      --  State refinements are visible upto the end the of the package body
-      --  declarations. Hide the refinements from visibility to restore the
-      --  original state conditions.
+         --  The owner of the declarations is a package [body]
 
-      if In_Package_Body then
-         Remove_Visible_Refinements (Spec_Id);
+         if Present (Pack_Decl) then
+
+            --  Capture all global references in a generic package or a body
+            --  after all nested generic subprograms and bodies were subjected
+            --  to the same processing.
+
+            if Is_Generic_Declaration_Or_Body (Pack_Decl) then
+               Save_Global_References_In_Contract
+                 (Templ  => Original_Node (Pack_Decl),
+                  Gen_Id => Corresponding_Spec_Of (Pack_Decl));
+            end if;
+
+            --  State refinements are visible upto the end the of the package
+            --  body declarations. Hide the state refinements from visibility
+            --  to restore the original state conditions.
+
+            if Nkind (Pack_Decl) = N_Package_Body then
+               Remove_Visible_Refinements (Corresponding_Spec (Pack_Decl));
+            end if;
+         end if;
       end if;
    end Analyze_Declarations;
 
@@ -2509,15 +2617,22 @@ package body Sem_Ch3 is
    begin
       Prev := Find_Type_Name (N);
 
-      --  The full view, if present, now points to the current type
-      --  If there is an incomplete partial view, set a link to it, to
-      --  simplify the retrieval of primitive operations of the type.
+      --  The type declaration may be subject to pragma Ghost with policy
+      --  Ignore. Set the mode now to ensure that any nodes generated during
+      --  analysis and expansion are properly flagged as ignored Ghost.
+
+      Set_Ghost_Mode (N, Prev);
+
+      --  The full view, if present, now points to the current type. If there
+      --  is an incomplete partial view, set a link to it, to simplify the
+      --  retrieval of primitive operations of the type.
 
       --  Ada 2005 (AI-50217): If the type was previously decorated when
       --  imported through a LIMITED WITH clause, it appears as incomplete
       --  but has no full view.
 
-      if Ekind (Prev) = E_Incomplete_Type and then Present (Full_View (Prev))
+      if Ekind (Prev) = E_Incomplete_Type
+        and then Present (Full_View (Prev))
       then
          T := Full_View (Prev);
          Set_Incomplete_View (N, Parent (Prev));
@@ -2549,7 +2664,7 @@ package body Sem_Ch3 is
 
          when N_Record_Definition =>
             if Present (Discriminant_Specifications (N)) then
-               Check_SPARK_Restriction
+               Check_SPARK_05_Restriction
                  ("discriminant type is not allowed",
                   Defining_Identifier
                     (First (Discriminant_Specifications (N))));
@@ -2573,7 +2688,6 @@ package body Sem_Ch3 is
          Set_Analyzed (T);
 
          case Nkind (Def) is
-
             when N_Access_To_Subprogram_Definition =>
                Access_Subprogram_Declaration (T, Def);
 
@@ -2607,12 +2721,6 @@ package body Sem_Ch3 is
                   Add_RACW_Features (Def_Id);
                end if;
 
-               --  Set no strict aliasing flag if config pragma seen
-
-               if Opt.No_Strict_Aliasing then
-                  Set_No_Strict_Aliasing (Base_Type (Def_Id));
-               end if;
-
             when N_Array_Type_Definition =>
                Array_Type_Declaration (T, Def);
 
@@ -2658,7 +2766,14 @@ package body Sem_Ch3 is
       --  Controlled type is not allowed in SPARK
 
       if Is_Visibly_Controlled (T) then
-         Check_SPARK_Restriction ("controlled type is not allowed", N);
+         Check_SPARK_05_Restriction ("controlled type is not allowed", N);
+      end if;
+
+      --  A type declared within a Ghost region is automatically Ghost
+      --  (SPARK RM 6.9(2)).
+
+      if Comes_From_Source (T) and then Ghost_Mode > None then
+         Set_Is_Ghost_Entity (T);
       end if;
 
       --  Some common processing for all types
@@ -2666,8 +2781,8 @@ package body Sem_Ch3 is
       Set_Depends_On_Private (T, Has_Private_Component (T));
       Check_Ops_From_Incomplete_Type;
 
-      --  Both the declared entity, and its anonymous base type if one
-      --  was created, need freeze nodes allocated.
+      --  Both the declared entity, and its anonymous base type if one was
+      --  created, need freeze nodes allocated.
 
       declare
          B : constant Entity_Id := Base_Type (T);
@@ -2741,6 +2856,14 @@ package body Sem_Ch3 is
          Generate_Definition (Def_Id);
       end if;
 
+      --  Propagate any pending access types whose finalization masters need to
+      --  be fully initialized from the partial to the full view. Guard against
+      --  an illegal full view that remains unanalyzed.
+
+      if Is_Type (Def_Id) and then Is_Incomplete_Or_Private_Type (Prev) then
+         Set_Pending_Access_Types (Def_Id, Pending_Access_Types (Prev));
+      end if;
+
       if Chars (Scope (Def_Id)) = Name_System
         and then Chars (Def_Id) = Name_Address
         and then Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (N)))
@@ -2758,8 +2881,21 @@ package body Sem_Ch3 is
       --  view, but which is the one that will be frozen.
 
       if Has_Aspects (N) then
-         if Prev /= Def_Id then
+
+         --  In most cases the partial view is a private type, and both views
+         --  appear in different declarative parts. In the unusual case where
+         --  the partial view is incomplete, perform the analysis on the
+         --  full view, to prevent freezing anomalies with the corresponding
+         --  class-wide type, which otherwise might be frozen before the
+         --  dispatch table is built.
+
+         if Prev /= Def_Id
+           and then Ekind (Prev) /= E_Incomplete_Type
+         then
             Analyze_Aspect_Specifications (N, Prev);
+
+         --  Normal case
+
          else
             Analyze_Aspect_Specifications (N, Def_Id);
          end if;
@@ -2775,7 +2911,7 @@ package body Sem_Ch3 is
       T : Entity_Id;
 
    begin
-      Check_SPARK_Restriction ("incomplete type is not allowed", N);
+      Check_SPARK_05_Restriction ("incomplete type is not allowed", N);
 
       Generate_Definition (Defining_Identifier (N));
 
@@ -2793,11 +2929,19 @@ package body Sem_Ch3 is
       Set_Is_First_Subtype (T, True);
       Set_Etype (T, T);
 
+      --  An incomplete type declared within a Ghost region is automatically
+      --  Ghost (SPARK RM 6.9(2)).
+
+      if Ghost_Mode > None then
+         Set_Is_Ghost_Entity (T);
+      end if;
+
       --  Ada 2005 (AI-326): Minimum decoration to give support to tagged
       --  incomplete types.
 
       if Tagged_Present (N) then
-         Set_Is_Tagged_Type (T);
+         Set_Is_Tagged_Type (T, True);
+         Set_No_Tagged_Streams_Pragma (T, No_Tagged_Streams);
          Make_Class_Wide_Type (T);
          Set_Direct_Primitive_Operations (T, New_Elmt_List);
       end if;
@@ -2829,6 +2973,7 @@ package body Sem_Ch3 is
 
    begin
       Set_Is_Tagged_Type (T);
+      Set_No_Tagged_Streams_Pragma (T, No_Tagged_Streams);
 
       Set_Is_Limited_Record (T, Limited_Present (Def)
                                   or else Task_Present (Def)
@@ -2898,9 +3043,22 @@ package body Sem_Ch3 is
       It    : Interp;
 
    begin
+      --  The number declaration may be subject to pragma Ghost with policy
+      --  Ignore. Set the mode now to ensure that any nodes generated during
+      --  analysis and expansion are properly flagged as ignored Ghost.
+
+      Set_Ghost_Mode (N);
+
       Generate_Definition (Id);
       Enter_Name (Id);
 
+      --  A number declared within a Ghost region is automatically Ghost
+      --  (SPARK RM 6.9(2)).
+
+      if Ghost_Mode > None then
+         Set_Is_Ghost_Entity (Id);
+      end if;
+
       --  This is an optimization of a common case of an integer literal
 
       if Nkind (E) = N_Integer_Literal then
@@ -2952,7 +3110,8 @@ package body Sem_Ch3 is
                   T := It.Typ;
 
                elsif It.Typ = Universal_Real
-                 or else It.Typ = Universal_Integer
+                       or else
+                     It.Typ = Universal_Integer
                then
                   --  Choose universal interpretation over any other
 
@@ -3039,6 +3198,15 @@ package body Sem_Ch3 is
       Seen    : Boolean := False;
 
    begin
+      --  The loop parameter in an element iterator over a formal container
+      --  is declared with an object declaration but no contracts apply.
+
+      if Ekind (Obj_Id) = E_Loop_Parameter then
+         return;
+      end if;
+
+      --  Constant related checks
+
       if Ekind (Obj_Id) = E_Constant then
 
          --  A constant cannot be effectively volatile. This check is only
@@ -3049,10 +3217,17 @@ package body Sem_Ch3 is
          if SPARK_Mode = On
            and then Is_Effectively_Volatile (Obj_Id)
            and then No (Corresponding_Generic_Association (Parent (Obj_Id)))
+
+           --  Don't give this for internally generated entities (such as the
+           --  FIRST and LAST temporaries generated for bounds).
+
+           and then Comes_From_Source (Obj_Id)
          then
             Error_Msg_N ("constant cannot be volatile", Obj_Id);
          end if;
 
+      --  Variable related checks
+
       else pragma Assert (Ekind (Obj_Id) = E_Variable);
 
          --  The following checks are only relevant when SPARK_Mode is on as
@@ -3100,6 +3275,23 @@ package body Sem_Ch3 is
             end if;
          end if;
 
+         if Is_Ghost_Entity (Obj_Id) then
+
+            --  A Ghost object cannot be effectively volatile (SPARK RM 6.9(8))
+
+            if Is_Effectively_Volatile (Obj_Id) then
+               Error_Msg_N ("ghost variable & cannot be volatile", Obj_Id);
+
+            --  A Ghost object cannot be imported or exported (SPARK RM 6.9(8))
+
+            elsif Is_Imported (Obj_Id) then
+               Error_Msg_N ("ghost object & cannot be imported", Obj_Id);
+
+            elsif Is_Exported (Obj_Id) then
+               Error_Msg_N ("ghost object & cannot be exported", Obj_Id);
+            end if;
+         end if;
+
          --  Analyze all external properties
 
          Prag := Get_Pragma (Obj_Id, Pragma_Async_Readers);
@@ -3135,14 +3327,25 @@ package body Sem_Ch3 is
          if Seen then
             Check_External_Properties (Obj_Id, AR_Val, AW_Val, ER_Val, EW_Val);
          end if;
+      end if;
+
+      --  Check whether the lack of indicator Part_Of agrees with the placement
+      --  of the object with respect to the state space.
 
-         --  Check whether the lack of indicator Part_Of agrees with the
-         --  placement of the variable with respect to the state space.
+      Prag := Get_Pragma (Obj_Id, Pragma_Part_Of);
 
-         Prag := Get_Pragma (Obj_Id, Pragma_Part_Of);
+      if No (Prag) then
+         Check_Missing_Part_Of (Obj_Id);
+      end if;
+
+      --  A ghost object cannot be imported or exported (SPARK RM 6.9(8))
 
-         if No (Prag) then
-            Check_Missing_Part_Of (Obj_Id);
+      if Is_Ghost_Entity (Obj_Id) then
+         if Is_Exported (Obj_Id) then
+            Error_Msg_N ("ghost object & cannot be exported", Obj_Id);
+
+         elsif Is_Imported (Obj_Id) then
+            Error_Msg_N ("ghost object & cannot be imported", Obj_Id);
          end if;
       end if;
    end Analyze_Object_Contract;
@@ -3171,6 +3374,17 @@ package body Sem_Ch3 is
       --  or a variant record type is encountered, Check_Restrictions is called
       --  indicating the count is unknown.
 
+      function Delayed_Aspect_Present return Boolean;
+      --  If the declaration has an expression that is an aggregate, and it
+      --  has aspects that require delayed analysis, the resolution of the
+      --  aggregate must be deferred to the freeze point of the objet. This
+      --  special processing was created for address clauses, but it must
+      --  also apply to Alignment. This must be done before the aspect
+      --  specifications are analyzed because we must handle the aggregate
+      --  before the analysis of the object declaration is complete.
+
+      --  Any other relevant delayed aspects on object declarations ???
+
       -----------------
       -- Count_Tasks --
       -----------------
@@ -3225,6 +3439,30 @@ package body Sem_Ch3 is
          end if;
       end Count_Tasks;
 
+      ----------------------------
+      -- Delayed_Aspect_Present --
+      ----------------------------
+
+      function Delayed_Aspect_Present return Boolean is
+         A    : Node_Id;
+         A_Id : Aspect_Id;
+
+      begin
+         if Present (Aspect_Specifications (N)) then
+            A    := First (Aspect_Specifications (N));
+            A_Id := Get_Aspect_Id (Chars (Identifier (A)));
+            while Present (A) loop
+               if A_Id = Aspect_Alignment or else A_Id = Aspect_Address then
+                  return True;
+               end if;
+
+               Next (A);
+            end loop;
+         end if;
+
+         return False;
+      end Delayed_Aspect_Present;
+
    --  Start of processing for Analyze_Object_Declaration
 
    begin
@@ -3259,24 +3497,31 @@ package body Sem_Ch3 is
                --  Enter_Name will handle the visibility.
 
                or else
-                (Is_Discriminal (Id)
+                 (Is_Discriminal (Id)
                    and then Ekind (Discriminal_Link (Id)) =
-                              E_Entry_Index_Parameter)
+                                              E_Entry_Index_Parameter)
 
                --  The current object is the renaming for a generic declared
                --  within the instance.
 
                or else
-                (Ekind (Prev_Entity) = E_Package
-                  and then Nkind (Parent (Prev_Entity)) =
-                                         N_Package_Renaming_Declaration
-                  and then not Comes_From_Source (Prev_Entity)
-                  and then Is_Generic_Instance (Renamed_Entity (Prev_Entity))))
+                 (Ekind (Prev_Entity) = E_Package
+                   and then Nkind (Parent (Prev_Entity)) =
+                                               N_Package_Renaming_Declaration
+                   and then not Comes_From_Source (Prev_Entity)
+                   and then
+                     Is_Generic_Instance (Renamed_Entity (Prev_Entity))))
          then
             Prev_Entity := Empty;
          end if;
       end if;
 
+      --  The object declaration may be subject to pragma Ghost with policy
+      --  Ignore. Set the mode now to ensure that any nodes generated during
+      --  analysis and expansion are properly flagged as ignored Ghost.
+
+      Set_Ghost_Mode (N, Prev_Entity);
+
       if Present (Prev_Entity) then
          Constant_Redeclaration (Id, N, T);
 
@@ -3392,11 +3637,21 @@ package body Sem_Ch3 is
             end if;
          end if;
 
-      --  If not a deferred constant, then object declaration freezes its type
+      --  If not a deferred constant, then the object declaration freezes
+      --  its type, unless the object is of an anonymous type and has delayed
+      --  aspects. In that case the type is frozen when the object itself is.
 
       else
          Check_Fully_Declared (T, N);
-         Freeze_Before (N, T);
+
+         if Has_Delayed_Aspects (Id)
+           and then Is_Array_Type (T)
+           and then Is_Itype (T)
+         then
+            Set_Has_Delayed_Freeze (T);
+         else
+            Freeze_Before (N, T);
+         end if;
       end if;
 
       --  If the object was created by a constrained array definition, then
@@ -3445,17 +3700,16 @@ package body Sem_Ch3 is
       --  and must not be unconstrained. (The only exception to this is the
       --  acceptance of declarations of constants of type String.)
 
-      if not
-        Nkind_In (Object_Definition (N), N_Identifier, N_Expanded_Name)
+      if not Nkind_In (Object_Definition (N), N_Expanded_Name, N_Identifier)
       then
-         Check_SPARK_Restriction
+         Check_SPARK_05_Restriction
            ("subtype mark required", Object_Definition (N));
 
       elsif Is_Array_Type (T)
         and then not Is_Constrained (T)
         and then T /= Standard_String
       then
-         Check_SPARK_Restriction
+         Check_SPARK_05_Restriction
            ("subtype mark of constrained type expected",
             Object_Definition (N));
       end if;
@@ -3463,7 +3717,7 @@ package body Sem_Ch3 is
       --  There are no aliased objects in SPARK
 
       if Aliased_Present (N) then
-         Check_SPARK_Restriction ("aliased object is not allowed", N);
+         Check_SPARK_05_Restriction ("aliased object is not allowed", N);
       end if;
 
       --  Process initialization expression if present and not in error
@@ -3523,8 +3777,9 @@ package body Sem_Ch3 is
 
          if Comes_From_Source (N)
            and then Expander_Active
-           and then Has_Following_Address_Clause (N)
            and then Nkind (E) = N_Aggregate
+           and then (Present (Following_Address_Clause (N))
+                      or else Delayed_Aspect_Present)
          then
             Set_Etype (E, T);
 
@@ -3567,8 +3822,8 @@ package body Sem_Ch3 is
            and then Is_Access_Constant (Etype (E))
          then
             Error_Msg_N
-              ("access to variable cannot be initialized "
-               & "with an access-to-constant expression", E);
+              ("access to variable cannot be initialized with an "
+               & "access-to-constant expression", E);
          end if;
 
          if not Assignment_OK (N) then
@@ -3618,11 +3873,22 @@ package body Sem_Ch3 is
            --  Only call test if needed
 
            and then Restriction_Check_Required (SPARK_05)
-           and then not Is_SPARK_Initialization_Expr (Original_Node (E))
+           and then not Is_SPARK_05_Initialization_Expr (Original_Node (E))
          then
-            Check_SPARK_Restriction
+            Check_SPARK_05_Restriction
               ("initialization expression is not appropriate", E);
          end if;
+
+         --  A formal parameter of a specific tagged type whose related
+         --  subprogram is subject to pragma Extensions_Visible with value
+         --  "False" cannot be implicitly converted to a class-wide type by
+         --  means of an initialization expression (SPARK RM 6.1.7(3)).
+
+         if Is_Class_Wide_Type (T) and then Is_EVF_Expression (E) then
+            Error_Msg_N
+              ("formal parameter with Extensions_Visible False cannot be "
+               & "implicitly converted to class-wide type", E);
+         end if;
       end if;
 
       --  If the No_Streams restriction is set, check that the type of the
@@ -3676,7 +3942,7 @@ package body Sem_Ch3 is
          --  only for constants of type string.
 
          if Is_String_Type (T) and then not Constant_Present (N) then
-            Check_SPARK_Restriction
+            Check_SPARK_05_Restriction
               ("declaration of object of unconstrained type not allowed", N);
          end if;
 
@@ -3760,6 +4026,55 @@ package body Sem_Ch3 is
             elsif Is_Interface (T) then
                null;
 
+            --  In GNATprove mode, Expand_Subtype_From_Expr does nothing. Thus,
+            --  we should prevent the generation of another Itype with the
+            --  same name as the one already generated, or we end up with
+            --  two identical types in GNATprove.
+
+            elsif GNATprove_Mode then
+               null;
+
+            --  If the type is an unchecked union, no subtype can be built from
+            --  the expression. Rewrite declaration as a renaming, which the
+            --  back-end can handle properly. This is a rather unusual case,
+            --  because most unchecked_union declarations have default values
+            --  for discriminants and are thus not indefinite.
+
+            elsif Is_Unchecked_Union (T) then
+               if Constant_Present (N) or else Nkind (E) = N_Function_Call then
+                  Set_Ekind (Id, E_Constant);
+               else
+                  Set_Ekind (Id, E_Variable);
+               end if;
+
+               --  An object declared within a Ghost region is automatically
+               --  Ghost (SPARK RM 6.9(2)).
+
+               if Comes_From_Source (Id) and then Ghost_Mode > None then
+                  Set_Is_Ghost_Entity (Id);
+
+                  --  The Ghost policy in effect at the point of declaration
+                  --  and at the point of completion must match
+                  --  (SPARK RM 6.9(14)).
+
+                  if Present (Prev_Entity)
+                    and then Is_Ghost_Entity (Prev_Entity)
+                  then
+                     Check_Ghost_Completion (Prev_Entity, Id);
+                  end if;
+               end if;
+
+               Rewrite (N,
+                 Make_Object_Renaming_Declaration (Loc,
+                   Defining_Identifier => Id,
+                   Subtype_Mark        => New_Occurrence_Of (T, Loc),
+                   Name                => E));
+
+               Set_Renamed_Object (Id, E);
+               Freeze_Before (N, T);
+               Set_Is_Frozen (Id);
+               return;
+
             else
                Expand_Subtype_From_Expr (N, T, Object_Definition (N), E);
                Act_T := Find_Type_Of_Object (Object_Definition (N), N);
@@ -3871,7 +4186,7 @@ package body Sem_Ch3 is
       --  true for variables so far (will be reset for a variable if and when
       --  we encounter a modification in the source).
 
-      Set_Never_Set_In_Source (Id, True);
+      Set_Never_Set_In_Source (Id);
 
       --  Now establish the proper kind and type of the object
 
@@ -3901,10 +4216,8 @@ package body Sem_Ch3 is
          --  the case of exception choice variables, it will already be true).
 
          if Present (E) then
-            Set_Has_Initial_Value (Id, True);
+            Set_Has_Initial_Value (Id);
          end if;
-
-         Set_Contract (Id, Make_Contract (Sloc (Id)));
       end if;
 
       --  Initialize alignment and size and capture alignment setting
@@ -3913,6 +4226,24 @@ package body Sem_Ch3 is
       Init_Esize                   (Id);
       Set_Optimize_Alignment_Flags (Id);
 
+      --  An object declared within a Ghost region is automatically Ghost
+      --  (SPARK RM 6.9(2)).
+
+      if Comes_From_Source (Id)
+        and then (Ghost_Mode > None
+                   or else (Present (Prev_Entity)
+                             and then Is_Ghost_Entity (Prev_Entity)))
+      then
+         Set_Is_Ghost_Entity (Id);
+
+         --  The Ghost policy in effect at the point of declaration and at the
+         --  point of completion must match (SPARK RM 6.9(14)).
+
+         if Present (Prev_Entity) and then Is_Ghost_Entity (Prev_Entity) then
+            Check_Ghost_Completion (Prev_Entity, Id);
+         end if;
+      end if;
+
       --  Deal with aliased case
 
       if Aliased_Present (N) then
@@ -4147,6 +4478,12 @@ package body Sem_Ch3 is
       Parent_Base : Entity_Id;
 
    begin
+      --  The private extension declaration may be subject to pragma Ghost with
+      --  policy Ignore. Set the mode now to ensure that any nodes generated
+      --  during analysis and expansion are properly flagged as ignored Ghost.
+
+      Set_Ghost_Mode (N);
+
       --  Ada 2005 (AI-251): Decorate all names in list of ancestor interfaces
 
       if Is_Non_Empty_List (Interface_List (N)) then
@@ -4192,9 +4529,7 @@ package body Sem_Ch3 is
       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
       Parent_Base := Base_Type (Parent_Type);
 
-      if Parent_Type = Any_Type
-        or else Etype (Parent_Type) = Any_Type
-      then
+      if Parent_Type = Any_Type or else Etype (Parent_Type) = Any_Type then
          Set_Ekind (T, Ekind (Parent_Type));
          Set_Etype (T, Any_Type);
          goto Leave;
@@ -4377,6 +4712,12 @@ package body Sem_Ch3 is
       R_Checks : Check_Result;
 
    begin
+      --  The subtype declaration may be subject to pragma Ghost with policy
+      --  Ignore. Set the mode now to ensure that any nodes generated during
+      --  analysis and expansion are properly flagged as ignored Ghost.
+
+      Set_Ghost_Mode (N);
+
       Generate_Definition (Id);
       Set_Is_Pure (Id, Is_Pure (Current_Scope));
       Init_Size_Align (Id);
@@ -4460,7 +4801,7 @@ package body Sem_Ch3 is
       if Is_Boolean_Type (T)
         and then Nkind (Subtype_Indication (N)) = N_Subtype_Indication
       then
-         Check_SPARK_Restriction
+         Check_SPARK_05_Restriction
            ("subtype of Boolean cannot have constraint", N);
       end if;
 
@@ -4482,7 +4823,7 @@ package body Sem_Ch3 is
                   if not
                     Nkind_In (One_Cstr, N_Identifier, N_Expanded_Name)
                   then
-                     Check_SPARK_Restriction
+                     Check_SPARK_05_Restriction
                        ("subtype mark required", One_Cstr);
 
                   --  String subtype must have a lower bound of 1 in SPARK.
@@ -4496,7 +4837,7 @@ package body Sem_Ch3 is
                      if Is_OK_Static_Expression (Low)
                        and then Expr_Value (Low) /= 1
                      then
-                        Check_SPARK_Restriction
+                        Check_SPARK_05_Restriction
                           ("String subtype must have lower bound of 1", N);
                      end if;
                   end if;
@@ -4518,7 +4859,7 @@ package body Sem_Ch3 is
          --  in SPARK.
 
          if Is_Array_Type (T) and then not Is_Constrained (T) then
-            Check_SPARK_Restriction
+            Check_SPARK_05_Restriction
               ("subtype of unconstrained array must have constraint", N);
          end if;
 
@@ -4582,13 +4923,13 @@ package body Sem_Ch3 is
 
             when Class_Wide_Kind =>
                Set_Ekind                (Id, E_Class_Wide_Subtype);
-               Set_First_Entity         (Id, First_Entity       (T));
-               Set_Last_Entity          (Id, Last_Entity        (T));
                Set_Class_Wide_Type      (Id, Class_Wide_Type    (T));
                Set_Cloned_Subtype       (Id, T);
                Set_Is_Tagged_Type       (Id, True);
                Set_Has_Unknown_Discriminants
                                         (Id, True);
+               Set_No_Tagged_Streams_Pragma
+                                        (Id, No_Tagged_Streams_Pragma (T));
 
                if Ekind (T) = E_Class_Wide_Subtype then
                   Set_Equivalent_Type   (Id, Equivalent_Type    (T));
@@ -4625,7 +4966,9 @@ package body Sem_Ch3 is
                end if;
 
                if Is_Tagged_Type (T) then
-                  Set_Is_Tagged_Type    (Id);
+                  Set_Is_Tagged_Type    (Id, True);
+                  Set_No_Tagged_Streams_Pragma
+                                        (Id, No_Tagged_Streams_Pragma (T));
                   Set_Is_Abstract_Type  (Id, Is_Abstract_Type (T));
                   Set_Direct_Primitive_Operations
                                         (Id, Direct_Primitive_Operations (T));
@@ -4654,6 +4997,8 @@ package body Sem_Ch3 is
 
                if Is_Tagged_Type (T) then
                   Set_Is_Tagged_Type              (Id);
+                  Set_No_Tagged_Streams_Pragma    (Id,
+                    No_Tagged_Streams_Pragma (T));
                   Set_Is_Abstract_Type            (Id, Is_Abstract_Type (T));
                   Set_Class_Wide_Type             (Id, Class_Wide_Type  (T));
                   Set_Direct_Primitive_Operations (Id,
@@ -4734,22 +5079,34 @@ package body Sem_Ch3 is
                Set_Is_Tagged_Type       (Id, Is_Tagged_Type        (T));
                Set_Last_Entity          (Id, Last_Entity           (T));
 
+               if Is_Tagged_Type (T) then
+                  Set_No_Tagged_Streams_Pragma
+                    (Id, No_Tagged_Streams_Pragma (T));
+               end if;
+
                if Has_Discriminants (T) then
-                  Set_Discriminant_Constraint (Id,
-                                           Discriminant_Constraint (T));
+                  Set_Discriminant_Constraint
+                    (Id, Discriminant_Constraint (T));
                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
                end if;
 
-            when E_Incomplete_Type =>
+            when Incomplete_Kind  =>
                if Ada_Version >= Ada_2005 then
 
                   --  In Ada 2005 an incomplete type can be explicitly tagged:
-                  --  propagate indication.
+                  --  propagate indication. Note that we also have to include
+                  --  subtypes for Ada 2012 extended use of incomplete types.
 
                   Set_Ekind              (Id, E_Incomplete_Subtype);
                   Set_Is_Tagged_Type     (Id, Is_Tagged_Type (T));
                   Set_Private_Dependents (Id, New_Elmt_List);
 
+                  if Is_Tagged_Type (Id) then
+                     Set_No_Tagged_Streams_Pragma
+                       (Id, No_Tagged_Streams_Pragma (T));
+                     Set_Direct_Primitive_Operations (Id, New_Elmt_List);
+                  end if;
+
                   --  Ada 2005 (AI-412): Decorate an incomplete subtype of an
                   --  incomplete type visible through a limited with clause.
 
@@ -4809,8 +5166,8 @@ package body Sem_Ch3 is
         and then
           (Nkind (Parent (Generic_Parent_Type (N))) /=
                                               N_Formal_Type_Declaration
-            or else Nkind
-              (Formal_Type_Definition (Parent (Generic_Parent_Type (N)))) /=
+            or else Nkind (Formal_Type_Definition
+                            (Parent (Generic_Parent_Type (N)))) /=
                                               N_Formal_Private_Type_Definition)
       then
          if Is_Tagged_Type (Id) then
@@ -4927,6 +5284,14 @@ package body Sem_Ch3 is
          end if;
       end if;
 
+      --  A type invariant applies to any subtype in its scope, in particular
+      --  to a generic actual.
+
+      if Has_Invariants (T) and then In_Open_Scopes (Scope (T)) then
+         Set_Has_Invariants (Id);
+         Set_Invariant_Procedure (Id, Invariant_Procedure (T));
+      end if;
+
       --  Make sure that generic actual types are properly frozen. The subtype
       --  is marked as a generic actual type when the enclosing instance is
       --  analyzed, so here we identify the subtype from the tree structure.
@@ -5092,7 +5457,7 @@ package body Sem_Ch3 is
          --  Check SPARK restriction requiring a subtype mark
 
          if not Nkind_In (Index, N_Identifier, N_Expanded_Name) then
-            Check_SPARK_Restriction ("subtype mark required", Index);
+            Check_SPARK_05_Restriction ("subtype mark required", Index);
          end if;
 
          --  Add a subtype declaration for each index of private array type
@@ -5169,7 +5534,8 @@ package body Sem_Ch3 is
          Set_Etype (Component_Typ, Element_Type);
 
          if not Nkind_In (Component_Typ, N_Identifier, N_Expanded_Name) then
-            Check_SPARK_Restriction ("subtype mark required", Component_Typ);
+            Check_SPARK_05_Restriction
+              ("subtype mark required", Component_Typ);
          end if;
 
       --  Ada 2005 (AI-230): Access Definition case
@@ -5229,12 +5595,13 @@ package body Sem_Ch3 is
 
          --  The constrained array type is a subtype of the unconstrained one
 
-         Set_Ekind          (T, E_Array_Subtype);
-         Init_Size_Align    (T);
-         Set_Etype          (T, Implicit_Base);
-         Set_Scope          (T, Current_Scope);
-         Set_Is_Constrained (T, True);
-         Set_First_Index    (T, First (Discrete_Subtype_Definitions (Def)));
+         Set_Ekind              (T, E_Array_Subtype);
+         Init_Size_Align        (T);
+         Set_Etype              (T, Implicit_Base);
+         Set_Scope              (T, Current_Scope);
+         Set_Is_Constrained     (T);
+         Set_First_Index        (T,
+           First (Discrete_Subtype_Definitions (Def)));
          Set_Has_Delayed_Freeze (T);
 
          --  Complete setup of implicit base type
@@ -5245,14 +5612,17 @@ package body Sem_Ch3 is
          Set_Has_Protected     (Implicit_Base, Has_Protected (Element_Type));
          Set_Component_Size    (Implicit_Base, Uint_0);
          Set_Packed_Array_Impl_Type (Implicit_Base, Empty);
-         Set_Has_Controlled_Component
-                               (Implicit_Base, Has_Controlled_Component
-                                                        (Element_Type)
-                                                 or else Is_Controlled
-                                                        (Element_Type));
-         Set_Finalize_Storage_Only
-                               (Implicit_Base, Finalize_Storage_Only
-                                                        (Element_Type));
+         Set_Has_Controlled_Component (Implicit_Base,
+           Has_Controlled_Component (Element_Type)
+             or else Is_Controlled  (Element_Type));
+         Set_Finalize_Storage_Only (Implicit_Base,
+           Finalize_Storage_Only (Element_Type));
+
+         --  Inherit the "ghostness" from the constrained array type
+
+         if Is_Ghost_Entity (T) or else Ghost_Mode > None then
+            Set_Is_Ghost_Entity (Implicit_Base);
+         end if;
 
       --  Unconstrained array case
 
@@ -5282,7 +5652,7 @@ package body Sem_Ch3 is
       Set_Packed_Array_Impl_Type (T, Empty);
 
       if Aliased_Present (Component_Definition (Def)) then
-         Check_SPARK_Restriction
+         Check_SPARK_05_Restriction
            ("aliased is not allowed", Component_Definition (Def));
          Set_Has_Aliased_Components (Etype (T));
       end if;
@@ -5468,7 +5838,11 @@ package body Sem_Ch3 is
             Set_Scope  (Typ, Current_Scope);
             Push_Scope (Typ);
 
-            Process_Formals (Parameter_Specifications (Spec), Spec);
+            --  Nothing to do if procedure is parameterless
+
+            if Present (Parameter_Specifications (Spec)) then
+               Process_Formals (Parameter_Specifications (Spec), Spec);
+            end if;
 
             if Nkind (Spec) = N_Access_Function_Definition then
                declare
@@ -5719,6 +6093,12 @@ package body Sem_Ch3 is
          Copy_Array_Base_Type_Attributes (Implicit_Base, Parent_Base);
 
          Set_Has_Delayed_Freeze (Implicit_Base, True);
+
+         --  Inherit the "ghostness" from the parent base type
+
+         if Is_Ghost_Entity (Parent_Base) or else Ghost_Mode > None then
+            Set_Is_Ghost_Entity (Implicit_Base);
+         end if;
       end Make_Implicit_Base;
 
    --  Start of processing for Build_Derived_Array_Type
@@ -6215,6 +6595,11 @@ package body Sem_Ch3 is
          Insert_Before (N, Type_Decl);
          Analyze (Type_Decl);
 
+         --  The anonymous base now has a full declaration, but this base
+         --  is not a first subtype.
+
+         Set_Is_First_Subtype (Implicit_Base, False);
+
          --  After the implicit base is analyzed its Etype needs to be changed
          --  to reflect the fact that it is derived from the parent type which
          --  was ignored during analysis. We also set the size at this point.
@@ -6311,14 +6696,19 @@ package body Sem_Ch3 is
 
          Analyze (N);
 
+         --  Propagate the aspects from the original type declaration to the
+         --  declaration of the implicit base.
+
+         Move_Aspects (From => Original_Node (N), To => Type_Decl);
+
          --  Apply a range check. Since this range expression doesn't have an
          --  Etype, we have to specifically pass the Source_Typ parameter. Is
          --  this right???
 
          if Nkind (Indic) = N_Subtype_Indication then
-            Apply_Range_Check (Range_Expression (Constraint (Indic)),
-                               Parent_Type,
-                               Source_Typ => Entity (Subtype_Mark (Indic)));
+            Apply_Range_Check
+              (Range_Expression (Constraint (Indic)), Parent_Type,
+               Source_Typ => Entity (Subtype_Mark (Indic)));
          end if;
       end if;
    end Build_Derived_Enumeration_Type;
@@ -6402,9 +6792,7 @@ package body Sem_Ch3 is
       --  If we did not have a range constraint, then set the range from the
       --  parent type. Otherwise, the Process_Subtype call has set the bounds.
 
-      if No_Constraint
-        or else not Has_Range_Constraint (Indic)
-      then
+      if No_Constraint or else not Has_Range_Constraint (Indic) then
          Set_Scalar_Range (Derived_Type,
            Make_Range (Loc,
              Low_Bound  => New_Copy_Tree (Type_Low_Bound  (Parent_Type)),
@@ -6540,14 +6928,12 @@ package body Sem_Ch3 is
       Is_Completion : Boolean;
       Derive_Subps  : Boolean := True)
    is
-      Loc        : constant Source_Ptr := Sloc (N);
-      Par_Base   : constant Entity_Id  := Base_Type (Parent_Type);
-      Par_Scope  : constant Entity_Id  := Scope (Par_Base);
-      Der_Base   : Entity_Id;
-      Discr      : Entity_Id;
-      Full_Der   : Entity_Id;
-      Full_P     : Entity_Id;
-      Last_Discr : Entity_Id;
+      Loc       : constant Source_Ptr := Sloc (N);
+      Par_Base  : constant Entity_Id  := Base_Type (Parent_Type);
+      Par_Scope : constant Entity_Id  := Scope (Par_Base);
+      Full_N    : constant Node_Id    := New_Copy_Tree (N);
+      Full_Der  : Entity_Id           := New_Copy (Derived_Type);
+      Full_P    : Entity_Id;
 
       procedure Build_Full_Derivation;
       --  Build full derivation, i.e. derive from the full view
@@ -6593,7 +6979,6 @@ package body Sem_Ch3 is
       --------------------
 
       procedure Copy_And_Build is
-         Full_N      : Node_Id;
          Full_Parent : Entity_Id := Parent_Type;
 
       begin
@@ -6630,8 +7015,6 @@ package body Sem_Ch3 is
             --  is originally a private declaration. Indicate that full view
             --  is internally generated.
 
-            Full_N := New_Copy_Tree (N);
-            Full_Der := New_Copy (Derived_Type);
             Set_Comes_From_Source (Full_N, False);
             Set_Comes_From_Source (Full_Der, False);
             Set_Parent (Full_Der, Full_N);
@@ -6668,7 +7051,8 @@ package body Sem_Ch3 is
 
             else
                Build_Derived_Type
-                 (Full_N, Full_Parent, Full_Der, True, Derive_Subps => False);
+                 (Full_N, Full_Parent, Full_Der,
+                  Is_Completion => False, Derive_Subps => False);
             end if;
 
             --  The full declaration has been introduced into the tree and
@@ -6687,7 +7071,8 @@ package body Sem_Ch3 is
             Set_Associated_Node_For_Itype (Full_Der, N);
             Set_Parent (Full_Der, N);
             Build_Derived_Type
-              (N, Full_Parent, Full_Der, True, Derive_Subps => False);
+              (N, Full_Parent, Full_Der,
+               Is_Completion => False, Derive_Subps => False);
          end if;
 
          Set_Has_Private_Declaration (Full_Der);
@@ -6801,6 +7186,28 @@ package body Sem_Ch3 is
 
                Set_Is_Frozen (Full_Der);
 
+               --  If the derived type has access discriminants, create
+               --  references to their anonymous types now, to prevent
+               --  back-end problems when their first use is in generated
+               --  bodies of primitives.
+
+               declare
+                  E : Entity_Id;
+
+               begin
+                  E := First_Entity (Full_Der);
+
+                  while Present (E) loop
+                     if Ekind (E) = E_Discriminant
+                       and then Ekind (Etype (E)) = E_Anonymous_Access_Type
+                     then
+                        Build_Itype_Reference (Etype (E), Decl);
+                     end if;
+
+                     Next_Entity (E);
+                  end loop;
+               end;
+
                --  Set up links between real entity and underlying record view
 
                Set_Underlying_Record_View (Derived_Type, Base_Type (Full_Der));
@@ -6817,76 +7224,75 @@ package body Sem_Ch3 is
          return;
 
       elsif Has_Discriminants (Parent_Type) then
-         if Present (Full_View (Parent_Type)) then
-            if not Is_Completion then
-               --  If this is not a completion, construct the implicit full
-               --  view by deriving from the full view of the parent type.
 
-               Build_Full_Derivation;
-
-            else
-               --  If this is a completion, the full view being built is itself
-               --  private. We build a subtype of the parent with the same
-               --  constraints as this full view, to convey to the back end the
-               --  constrained components and the size of this subtype. If the
-               --  parent is constrained, its full view can serve as the
-               --  underlying full view of the derived type.
-
-               if No (Discriminant_Specifications (N)) then
-                  if Nkind (Subtype_Indication (Type_Definition (N))) =
-                                                        N_Subtype_Indication
-                  then
-                     Build_Underlying_Full_View (N, Derived_Type, Parent_Type);
+         --  Build partial view of derived type from partial view of parent.
+         --  This must be done before building the full derivation because the
+         --  second derivation will modify the discriminants of the first and
+         --  the discriminants are chained with the rest of the components in
+         --  the full derivation.
 
-                  elsif Is_Constrained (Full_View (Parent_Type)) then
-                     Set_Underlying_Full_View
-                       (Derived_Type, Full_View (Parent_Type));
-                  end if;
+         Build_Derived_Record_Type
+           (N, Parent_Type, Derived_Type, Derive_Subps);
 
-               else
-                  --  If there are new discriminants, the parent subtype is
-                  --  constrained by them, but it is not clear how to build
-                  --  the Underlying_Full_View in this case???
+         --  Build the full derivation if this is not the anonymous derived
+         --  base type created by Build_Derived_Record_Type in the constrained
+         --  case (see point 5. of its head comment) since we build it for the
+         --  derived subtype. And skip it for protected types altogether, as
+         --  gigi does not use these types directly.
 
-                  null;
-               end if;
-            end if;
-         end if;
+         if Present (Full_View (Parent_Type))
+           and then not Is_Itype (Derived_Type)
+           and then not (Ekind (Full_View (Parent_Type)) in Protected_Kind)
+         then
+            declare
+               Der_Base   : constant Entity_Id := Base_Type (Derived_Type);
+               Discr      : Entity_Id;
+               Last_Discr : Entity_Id;
 
-         --  Build partial view of derived type from partial view of parent
+            begin
+               --  If this is not a completion, construct the implicit full
+               --  view by deriving from the full view of the parent type.
+               --  But if this is a completion, the derived private type
+               --  being built is a full view and the full derivation can
+               --  only be its underlying full view.
 
-         Build_Derived_Record_Type
-           (N, Parent_Type, Derived_Type, Derive_Subps);
+               Build_Full_Derivation;
 
-         if Present (Full_View (Parent_Type)) and then not Is_Completion then
-            --  Install full view in derived type (base type and subtype)
+               if not Is_Completion then
+                  Set_Full_View (Derived_Type, Full_Der);
+               else
+                  Set_Underlying_Full_View (Derived_Type, Full_Der);
+               end if;
 
-            Der_Base := Base_Type (Derived_Type);
-            Set_Full_View (Derived_Type, Full_Der);
-            Set_Full_View (Der_Base, Base_Type (Full_Der));
+               if not Is_Base_Type (Derived_Type) then
+                  Set_Full_View (Der_Base, Base_Type (Full_Der));
+               end if;
 
-            --  Copy the discriminant list from full view to the partial views
-            --  (base type and its subtype). Gigi requires that the partial and
-            --  full views have the same discriminants.
+               --  Copy the discriminant list from full view to the partial
+               --  view (base type and its subtype). Gigi requires that the
+               --  partial and full views have the same discriminants.
 
-            --  Note that since the partial view is pointing to discriminants
-            --  in the full view, their scope will be that of the full view.
-            --  This might cause some front end problems and need adjustment???
+               --  Note that since the partial view points to discriminants
+               --  in the full view, their scope will be that of the full
+               --  view. This might cause some front end problems and need
+               --  adjustment???
 
-            Discr := First_Discriminant (Base_Type (Full_Der));
-            Set_First_Entity (Der_Base, Discr);
+               Discr := First_Discriminant (Base_Type (Full_Der));
+               Set_First_Entity (Der_Base, Discr);
 
-            loop
-               Last_Discr := Discr;
-               Next_Discriminant (Discr);
-               exit when No (Discr);
-            end loop;
+               loop
+                  Last_Discr := Discr;
+                  Next_Discriminant (Discr);
+                  exit when No (Discr);
+               end loop;
 
-            Set_Last_Entity (Der_Base, Last_Discr);
+               Set_Last_Entity (Der_Base, Last_Discr);
+               Set_First_Entity (Derived_Type, First_Entity (Der_Base));
+               Set_Last_Entity  (Derived_Type, Last_Entity  (Der_Base));
 
-            Set_First_Entity (Derived_Type, First_Entity (Der_Base));
-            Set_Last_Entity  (Derived_Type, Last_Entity  (Der_Base));
-            Set_Stored_Constraint (Full_Der, Stored_Constraint (Derived_Type));
+               Set_Stored_Constraint
+                 (Full_Der, Stored_Constraint (Derived_Type));
+            end;
          end if;
 
       elsif Present (Full_View (Parent_Type))
@@ -6902,19 +7308,16 @@ package body Sem_Ch3 is
             return;
          end if;
 
-         if not Is_Completion then
-            --  If this is not a completion, construct the implicit full view
-            --  by deriving from the full view of the parent type.
+         --  If this is not a completion, construct the implicit full view by
+         --  deriving from the full view of the parent type. But if this is a
+         --  completion, the derived private type being built is a full view
+         --  and the full derivation can only be its underlying full view.
 
-            Build_Full_Derivation;
-            Set_Full_View (Derived_Type, Full_Der);
+         Build_Full_Derivation;
 
+         if not Is_Completion then
+            Set_Full_View (Derived_Type, Full_Der);
          else
-            --  If this is a completion, the full view being built is itself
-            --  private. Construct an underlying full view by deriving from
-            --  the full view of the parent type.
-
-            Build_Full_Derivation;
             Set_Underlying_Full_View (Derived_Type, Full_Der);
          end if;
 
@@ -7610,7 +8013,7 @@ package body Sem_Ch3 is
          if not Has_Discriminants (Parent_Base)
            or else
              (Has_Unknown_Discriminants (Parent_Base)
-                and then Is_Private_Type (Parent_Base))
+               and then Is_Private_Type (Parent_Base))
          then
             Error_Msg_N
               ("invalid constraint: type has no discriminant",
@@ -7734,7 +8137,7 @@ package body Sem_Ch3 is
 
          Build_Derived_Type
            (New_Decl, Parent_Base, New_Base,
-            Is_Completion => True, Derive_Subps => False);
+            Is_Completion => False, Derive_Subps => False);
 
          --  ??? This needs re-examination to determine whether the
          --  above call can simply be replaced by a call to Analyze.
@@ -7760,9 +8163,9 @@ package body Sem_Ch3 is
                while Present (C) loop
                   Expr := Node (C);
 
-                  --  It is safe here to call New_Copy_Tree since
-                  --  Force_Evaluation was called on each constraint in
-                  --  Build_Discriminant_Constraints.
+                  --  It is safe here to call New_Copy_Tree since we called
+                  --  Force_Evaluation on each constraint previously
+                  --  in Build_Discriminant_Constraints.
 
                   Append (New_Copy_Tree (Expr), To => Constr_List);
 
@@ -7969,7 +8372,7 @@ package body Sem_Ch3 is
 
       elsif Is_Limited_Record (Parent_Type)
         or else (Present (Full_View (Parent_Type))
-                   and then Is_Limited_Record (Full_View (Parent_Type)))
+                  and then Is_Limited_Record (Full_View (Parent_Type)))
       then
          if not Is_Interface (Parent_Type)
            or else Is_Synchronized_Interface (Parent_Type)
@@ -8054,7 +8457,7 @@ package body Sem_Ch3 is
 
                declare
                   Corr_Disc : constant Entity_Id :=
-                      Corresponding_Discriminant (Discrim);
+                                Corresponding_Discriminant (Discrim);
                   Disc_Type : constant Entity_Id := Etype (Discrim);
                   Corr_Type : Entity_Id;
 
@@ -8155,7 +8558,7 @@ package body Sem_Ch3 is
          Set_Is_Constrained
            (Derived_Type,
             not (Inherit_Discrims
-                   or else Has_Unknown_Discriminants (Derived_Type)));
+                  or else Has_Unknown_Discriminants (Derived_Type)));
       end if;
 
       --  STEP 3: initialize fields of derived type
@@ -8180,11 +8583,16 @@ package body Sem_Ch3 is
       --  Fields inherited from the Parent_Type
 
       Set_Has_Specified_Layout
-        (Derived_Type, Has_Specified_Layout (Parent_Type));
+        (Derived_Type, Has_Specified_Layout     (Parent_Type));
       Set_Is_Limited_Composite
-        (Derived_Type, Is_Limited_Composite (Parent_Type));
+        (Derived_Type, Is_Limited_Composite     (Parent_Type));
       Set_Is_Private_Composite
-        (Derived_Type, Is_Private_Composite (Parent_Type));
+        (Derived_Type, Is_Private_Composite     (Parent_Type));
+
+      if Is_Tagged_Type (Parent_Type) then
+         Set_No_Tagged_Streams_Pragma
+           (Derived_Type, No_Tagged_Streams_Pragma (Parent_Type));
+      end if;
 
       --  Fields inherited from the Parent_Base
 
@@ -8205,7 +8613,6 @@ package body Sem_Ch3 is
       --  Fields inherited from the Parent_Base for record types
 
       if Is_Record_Type (Derived_Type) then
-
          declare
             Parent_Full : Entity_Id;
 
@@ -8332,7 +8739,7 @@ package body Sem_Ch3 is
                if Is_Itype (Derived_Type) then
                   declare
                      Def : constant Node_Id :=
-                       Associated_Node_For_Itype (Derived_Type);
+                             Associated_Node_For_Itype (Derived_Type);
                   begin
                      if Present (Def)
                        and then Nkind (Def) = N_Full_Type_Declaration
@@ -8342,17 +8749,57 @@ package body Sem_Ch3 is
                      end if;
                   end;
                end if;
-            end;
-         end if;
 
-      else
-         Set_Is_Packed (Derived_Type, Is_Packed (Parent_Base));
-         Set_Has_Non_Standard_Rep
-                       (Derived_Type, Has_Non_Standard_Rep (Parent_Base));
-      end if;
-
-      --  STEP 4: Inherit components from the parent base and constrain them.
-      --          Apply the second transformation described in point 6. above.
+               --  Propagate inherited invariant information of parents
+               --  and progenitors
+
+               if Ada_Version >= Ada_2012
+                 and then not Is_Interface (Derived_Type)
+               then
+                  if Has_Inheritable_Invariants (Parent_Type) then
+                     Set_Has_Invariants (Derived_Type);
+                     Set_Has_Inheritable_Invariants (Derived_Type);
+
+                  elsif not Is_Empty_Elmt_List (Ifaces_List) then
+                     declare
+                        AI : Elmt_Id;
+
+                     begin
+                        AI := First_Elmt (Ifaces_List);
+                        while Present (AI) loop
+                           if Has_Inheritable_Invariants (Node (AI)) then
+                              Set_Has_Invariants (Derived_Type);
+                              Set_Has_Inheritable_Invariants (Derived_Type);
+
+                              exit;
+                           end if;
+
+                           Next_Elmt (AI);
+                        end loop;
+                     end;
+                  end if;
+               end if;
+
+               --  A type extension is automatically Ghost when one of its
+               --  progenitors is Ghost (SPARK RM 6.9(9)). This property is
+               --  also inherited when the parent type is Ghost, but this is
+               --  done in Build_Derived_Type as the mechanism also handles
+               --  untagged derivations.
+
+               if Implements_Ghost_Interface (Derived_Type) then
+                  Set_Is_Ghost_Entity (Derived_Type);
+               end if;
+            end;
+         end if;
+
+      else
+         Set_Is_Packed (Derived_Type, Is_Packed (Parent_Base));
+         Set_Has_Non_Standard_Rep
+                       (Derived_Type, Has_Non_Standard_Rep (Parent_Base));
+      end if;
+
+      --  STEP 4: Inherit components from the parent base and constrain them.
+      --          Apply the second transformation described in point 6. above.
 
       if (not Is_Empty_Elmt_List (Discs) or else Inherit_Discrims)
         or else not Has_Discriminants (Parent_Type)
@@ -8536,6 +8983,12 @@ package body Sem_Ch3 is
       Set_RM_Size        (Derived_Type, RM_Size        (Parent_Type));
       Set_Is_Controlled  (Derived_Type, Is_Controlled  (Parent_Type));
       Set_Is_Tagged_Type (Derived_Type, Is_Tagged_Type (Parent_Type));
+      Set_Is_Volatile    (Derived_Type, Is_Volatile    (Parent_Type));
+
+      if Is_Tagged_Type (Derived_Type) then
+         Set_No_Tagged_Streams_Pragma
+           (Derived_Type, No_Tagged_Streams_Pragma (Parent_Type));
+      end if;
 
       --  If the parent has primitive routines, set the derived type link
 
@@ -8547,12 +9000,11 @@ package body Sem_Ch3 is
       --  type may be set in the private part, and not propagated to the
       --  subtype until later, so we obtain the convention from the base type.
 
-      Set_Convention     (Derived_Type, Convention     (Parent_Base));
+      Set_Convention (Derived_Type, Convention (Parent_Base));
 
       --  Set SSO default for record or array type
 
-      if (Is_Array_Type (Derived_Type)
-          or else Is_Record_Type (Derived_Type))
+      if (Is_Array_Type (Derived_Type) or else Is_Record_Type (Derived_Type))
         and then Is_Base_Type (Derived_Type)
       then
          Set_Default_SSO (Derived_Type);
@@ -8568,62 +9020,21 @@ package body Sem_Ch3 is
          Set_Has_Predicates (Derived_Type);
       end if;
 
-      --  The derived type inherits the representation clauses of the parent.
-      --  However, for a private type that is completed by a derivation, there
-      --  may be operation attributes that have been specified already (stream
-      --  attributes and External_Tag) and those must be provided. Finally,
-      --  if the partial view is a private extension, the representation items
-      --  of the parent have been inherited already, and should not be chained
-      --  twice to the derived type.
+      --  The derived type inherits the representation clauses of the parent
 
-      if Is_Tagged_Type (Parent_Type)
-        and then Present (First_Rep_Item (Derived_Type))
-      then
-         --  The existing items are either operational items or items inherited
-         --  from a private extension declaration.
-
-         declare
-            Rep : Node_Id;
-            --  Used to iterate over representation items of the derived type
-
-            Last_Rep : Node_Id;
-            --  Last representation item of the (non-empty) representation
-            --  item list of the derived type.
-
-            Found : Boolean := False;
-
-         begin
-            Rep      := First_Rep_Item (Derived_Type);
-            Last_Rep := Rep;
-            while Present (Rep) loop
-               if Rep = First_Rep_Item (Parent_Type) then
-                  Found := True;
-                  exit;
-
-               else
-                  Rep := Next_Rep_Item (Rep);
-
-                  if Present (Rep) then
-                     Last_Rep := Rep;
-                  end if;
-               end if;
-            end loop;
+      Inherit_Rep_Item_Chain (Derived_Type, Parent_Type);
 
-            --  Here if we either encountered the parent type's first rep
-            --  item on the derived type's rep item list (in which case
-            --  Found is True, and we have nothing else to do), or if we
-            --  reached the last rep item of the derived type, which is
-            --  Last_Rep, in which case we further chain the parent type's
-            --  rep items to those of the derived type.
+      --  Propagate the attributes related to pragma Default_Initial_Condition
+      --  from the parent type to the private extension. A derived type always
+      --  inherits the default initial condition flag from the parent type. If
+      --  the derived type carries its own Default_Initial_Condition pragma,
+      --  the flag is later reset in Analyze_Pragma. Note that both flags are
+      --  mutually exclusive.
 
-            if not Found then
-               Set_Next_Rep_Item (Last_Rep, First_Rep_Item (Parent_Type));
-            end if;
-         end;
-
-      else
-         Set_First_Rep_Item (Derived_Type, First_Rep_Item (Parent_Type));
-      end if;
+      Propagate_Default_Init_Cond_Attributes
+        (From_Typ             => Parent_Type,
+         To_Typ               => Derived_Type,
+         Parent_To_Derivation => True);
 
       --  If the parent type has delayed rep aspects, then mark the derived
       --  type as possibly inheriting a delayed rep aspect.
@@ -8632,6 +9043,13 @@ package body Sem_Ch3 is
          Set_May_Inherit_Delayed_Rep_Aspects (Derived_Type);
       end if;
 
+      --  Propagate the attributes related to pragma Ghost from the parent type
+      --  to the derived type or type extension (SPARK RM 6.9(9)).
+
+      if Is_Ghost_Entity (Parent_Type) then
+         Set_Is_Ghost_Entity (Derived_Type);
+      end if;
+
       --  Type dependent processing
 
       case Ekind (Parent_Type) is
@@ -8722,7 +9140,8 @@ package body Sem_Ch3 is
       --  and in family bounds.
 
       if Is_Concurrent_Type (Current_Scope)
-        or else Is_Limited_Type (Current_Scope)
+           or else
+         Is_Limited_Type    (Current_Scope)
       then
          CR_Disc := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
 
@@ -8843,8 +9262,7 @@ package body Sem_Ch3 is
 
          elsif Nkind (Constr) = N_Range
            or else (Nkind (Constr) = N_Attribute_Reference
-                     and then
-                    Attribute_Name (Constr) = Name_Range)
+                     and then Attribute_Name (Constr) = Name_Range)
          then
             Error_Msg_N
               ("a range is not a valid discriminant constraint", Constr);
@@ -9180,6 +9598,7 @@ package body Sem_Ch3 is
 
       if Is_Tagged_Type (T) then
          Set_Is_Tagged_Type (Def_Id);
+         Set_No_Tagged_Streams_Pragma (Def_Id, No_Tagged_Streams_Pragma (T));
          Make_Class_Wide_Type (Def_Id);
       end if;
 
@@ -9701,6 +10120,16 @@ package body Sem_Ch3 is
                   then
                      null;
 
+                  --  A null extension is not obliged to override an inherited
+                  --  procedure subject to pragma Extensions_Visible with value
+                  --  False and at least one controlling OUT parameter
+                  --  (SPARK RM 6.1.7(6)).
+
+                  elsif Is_Null_Extension (T)
+                    and then Is_EVF_Procedure (Subp)
+                  then
+                     null;
+
                   else
                      Error_Msg_NE
                        ("type must be declared abstract or & overridden",
@@ -9744,6 +10173,16 @@ package body Sem_Ch3 is
                                 ("\& subprogram# is not visible",
                                  T, Subp);
 
+                           --  Clarify the case where a non-null extension must
+                           --  override inherited procedure subject to pragma
+                           --  Extensions_Visible with value False and at least
+                           --  one controlling OUT param.
+
+                           elsif Is_EVF_Procedure (E) then
+                              Error_Msg_NE
+                                ("\& # is subject to Extensions_Visible False",
+                                 T, Subp);
+
                            else
                               Error_Msg_NE
                                 ("\& has been inherited from subprogram #",
@@ -9759,46 +10198,34 @@ package body Sem_Ch3 is
                elsif Is_Concurrent_Record_Type (T)
                  and then Present (Interfaces (T))
                then
-                  --  If an inherited subprogram is implemented by a protected
-                  --  procedure or an entry, then the first parameter of the
-                  --  inherited subprogram shall be of mode OUT or IN OUT, or
-                  --  an access-to-variable parameter (RM 9.4(11.9/3))
-
-                  if Is_Protected_Type (Corresponding_Concurrent_Type (T))
-                    and then Ekind (First_Formal (Subp)) = E_In_Parameter
-                    and then Ekind (Subp) /= E_Function
-                    and then not Is_Predefined_Dispatching_Operation (Subp)
-                  then
-                     Error_Msg_PT (T, Subp);
+                  --  There is no need to check here RM 9.4(11.9/3) since we
+                  --  are processing the corresponding record type and the
+                  --  mode of the overriding subprograms was verified by
+                  --  Check_Conformance when the corresponding concurrent
+                  --  type declaration was analyzed.
 
-                  --  Some other kind of overriding failure
-
-                  else
-                     Error_Msg_NE
-                       ("interface subprogram & must be overridden",
-                        T, Subp);
+                  Error_Msg_NE
+                    ("interface subprogram & must be overridden", T, Subp);
 
-                     --  Examine primitive operations of synchronized type,
-                     --  to find homonyms that have the wrong profile.
+                  --  Examine primitive operations of synchronized type to find
+                  --  homonyms that have the wrong profile.
 
-                     declare
-                        Prim : Entity_Id;
+                  declare
+                     Prim : Entity_Id;
 
-                     begin
-                        Prim :=
-                          First_Entity (Corresponding_Concurrent_Type (T));
-                        while Present (Prim) loop
-                           if Chars (Prim) = Chars (Subp) then
-                              Error_Msg_NE
-                                ("profile is not type conformant with "
-                                   & "prefixed view profile of "
-                                   & "inherited operation&", Prim, Subp);
-                           end if;
+                  begin
+                     Prim := First_Entity (Corresponding_Concurrent_Type (T));
+                     while Present (Prim) loop
+                        if Chars (Prim) = Chars (Subp) then
+                           Error_Msg_NE
+                             ("profile is not type conformant with prefixed "
+                              & "view profile of inherited operation&",
+                              Prim, Subp);
+                        end if;
 
-                           Next_Entity (Prim);
-                        end loop;
-                     end;
-                  end if;
+                        Next_Entity (Prim);
+                     end loop;
+                  end;
                end if;
 
             else
@@ -9813,6 +10240,20 @@ package body Sem_Ch3 is
                Error_Msg_Node_2 := Subp;
                Error_Msg_N ("nonabstract type& has abstract subprogram&!", T);
             end if;
+
+         --  A subprogram subject to pragma Extensions_Visible with value
+         --  "True" cannot override a subprogram subject to the same pragma
+         --  with value "False" (SPARK RM 6.1.7(5)).
+
+         elsif Extensions_Visible_Status (Subp) = Extensions_Visible_True
+           and then Present (Overridden_Operation (Subp))
+           and then Extensions_Visible_Status (Overridden_Operation (Subp)) =
+                    Extensions_Visible_False
+         then
+            Error_Msg_Sloc := Sloc (Overridden_Operation (Subp));
+            Error_Msg_N
+              ("subprogram & with Extensions_Visible True cannot override "
+               & "subprogram # with Extensions_Visible False", Subp);
          end if;
 
          --  Ada 2012 (AI05-0030): Perform checks related to pragma Implemented
@@ -9953,10279 +10394,10540 @@ package body Sem_Ch3 is
       end if;
    end Check_Aliased_Component_Types;
 
-   ----------------------
-   -- Check_Completion --
-   ----------------------
+   ---------------------------------------
+   -- Check_Anonymous_Access_Components --
+   ---------------------------------------
 
-   procedure Check_Completion (Body_Id : Node_Id := Empty) is
-      E : Entity_Id;
+   procedure Check_Anonymous_Access_Components
+      (Typ_Decl  : Node_Id;
+       Typ       : Entity_Id;
+       Prev      : Entity_Id;
+       Comp_List : Node_Id)
+   is
+      Loc         : constant Source_Ptr := Sloc (Typ_Decl);
+      Anon_Access : Entity_Id;
+      Acc_Def     : Node_Id;
+      Comp        : Node_Id;
+      Comp_Def    : Node_Id;
+      Decl        : Node_Id;
+      Type_Def    : Node_Id;
 
-      procedure Post_Error;
-      --  Post error message for lack of completion for entity E
+      procedure Build_Incomplete_Type_Declaration;
+      --  If the record type contains components that include an access to the
+      --  current record, then create an incomplete type declaration for the
+      --  record, to be used as the designated type of the anonymous access.
+      --  This is done only once, and only if there is no previous partial
+      --  view of the type.
 
-      ----------------
-      -- Post_Error --
-      ----------------
+      function Designates_T (Subt : Node_Id) return Boolean;
+      --  Check whether a node designates the enclosing record type, or 'Class
+      --  of that type
 
-      procedure Post_Error is
+      function Mentions_T (Acc_Def : Node_Id) return Boolean;
+      --  Check whether an access definition includes a reference to
+      --  the enclosing record type. The reference can be a subtype mark
+      --  in the access definition itself, a 'Class attribute reference, or
+      --  recursively a reference appearing in a parameter specification
+      --  or result definition of an access_to_subprogram definition.
 
-         procedure Missing_Body;
-         --  Output missing body message
+      --------------------------------------
+      -- Build_Incomplete_Type_Declaration --
+      --------------------------------------
 
-         ------------------
-         -- Missing_Body --
-         ------------------
+      procedure Build_Incomplete_Type_Declaration is
+         Decl  : Node_Id;
+         Inc_T : Entity_Id;
+         H     : Entity_Id;
 
-         procedure Missing_Body is
-         begin
-            --  Spec is in same unit, so we can post on spec
+         --  Is_Tagged indicates whether the type is tagged. It is tagged if
+         --  it's "is new ... with record" or else "is tagged record ...".
 
-            if In_Same_Source_Unit (Body_Id, E) then
-               Error_Msg_N ("missing body for &", E);
+         Is_Tagged : constant Boolean :=
+             (Nkind (Type_Definition (Typ_Decl)) = N_Derived_Type_Definition
+               and then
+                 Present (Record_Extension_Part (Type_Definition (Typ_Decl))))
+           or else
+             (Nkind (Type_Definition (Typ_Decl)) = N_Record_Definition
+               and then Tagged_Present (Type_Definition (Typ_Decl)));
 
-            --  Spec is in a separate unit, so we have to post on the body
+      begin
+         --  If there is a previous partial view, no need to create a new one
+         --  If the partial view, given by Prev, is incomplete,  If Prev is
+         --  a private declaration, full declaration is flagged accordingly.
 
-            else
-               Error_Msg_NE ("missing body for & declared#!", Body_Id, E);
+         if Prev /= Typ then
+            if Is_Tagged then
+               Make_Class_Wide_Type (Prev);
+               Set_Class_Wide_Type (Typ, Class_Wide_Type (Prev));
+               Set_Etype (Class_Wide_Type (Typ), Typ);
             end if;
-         end Missing_Body;
 
-      --  Start of processing for Post_Error
+            return;
 
-      begin
-         if not Comes_From_Source (E) then
+         elsif Has_Private_Declaration (Typ) then
 
-            if Ekind_In (E, E_Task_Type, E_Protected_Type) then
-               --  It may be an anonymous protected type created for a
-               --  single variable. Post error on variable, if present.
+            --  If we refer to T'Class inside T, and T is the completion of a
+            --  private type, then make sure the class-wide type exists.
 
-               declare
-                  Var : Entity_Id;
+            if Is_Tagged then
+               Make_Class_Wide_Type (Typ);
+            end if;
 
-               begin
-                  Var := First_Entity (Current_Scope);
-                  while Present (Var) loop
-                     exit when Etype (Var) = E
-                       and then Comes_From_Source (Var);
+            return;
 
-                     Next_Entity (Var);
-                  end loop;
+         --  If there was a previous anonymous access type, the incomplete
+         --  type declaration will have been created already.
 
-                  if Present (Var) then
-                     E := Var;
-                  end if;
-               end;
+         elsif Present (Current_Entity (Typ))
+           and then Ekind (Current_Entity (Typ)) = E_Incomplete_Type
+           and then Full_View (Current_Entity (Typ)) = Typ
+         then
+            if Is_Tagged
+              and then Comes_From_Source (Current_Entity (Typ))
+              and then not Is_Tagged_Type (Current_Entity (Typ))
+            then
+               Make_Class_Wide_Type (Typ);
+               Error_Msg_N
+                 ("incomplete view of tagged type should be declared tagged??",
+                  Parent (Current_Entity (Typ)));
             end if;
-         end if;
-
-         --  If a generated entity has no completion, then either previous
-         --  semantic errors have disabled the expansion phase, or else we had
-         --  missing subunits, or else we are compiling without expansion,
-         --  or else something is very wrong.
-
-         if not Comes_From_Source (E) then
-            pragma Assert
-              (Serious_Errors_Detected > 0
-                or else Configurable_Run_Time_Violations > 0
-                or else Subunits_Missing
-                or else not Expander_Active);
             return;
 
-         --  Here for source entity
-
          else
-            --  Here if no body to post the error message, so we post the error
-            --  on the declaration that has no completion. This is not really
-            --  the right place to post it, think about this later ???
+            Inc_T := Make_Defining_Identifier (Loc, Chars (Typ));
+            Decl  := Make_Incomplete_Type_Declaration (Loc, Inc_T);
 
-            if No (Body_Id) then
-               if Is_Type (E) then
-                  Error_Msg_NE
-                    ("missing full declaration for }", Parent (E), E);
-               else
-                  Error_Msg_NE ("missing body for &", Parent (E), E);
-               end if;
+            --  Type has already been inserted into the current scope. Remove
+            --  it, and add incomplete declaration for type, so that subsequent
+            --  anonymous access types can use it. The entity is unchained from
+            --  the homonym list and from immediate visibility. After analysis,
+            --  the entity in the incomplete declaration becomes immediately
+            --  visible in the record declaration that follows.
 
-            --  Package body has no completion for a declaration that appears
-            --  in the corresponding spec. Post error on the body, with a
-            --  reference to the non-completed declaration.
+            H := Current_Entity (Typ);
 
+            if H = Typ then
+               Set_Name_Entity_Id (Chars (Typ), Homonym (Typ));
             else
-               Error_Msg_Sloc := Sloc (E);
-
-               if Is_Type (E) then
-                  Error_Msg_NE ("missing full declaration for }!", Body_Id, E);
+               while Present (H)
+                 and then Homonym (H) /= Typ
+               loop
+                  H := Homonym (Typ);
+               end loop;
 
-               elsif Is_Overloadable (E)
-                 and then Current_Entity_In_Scope (E) /= E
-               then
-                  --  It may be that the completion is mistyped and appears as
-                  --  a distinct overloading of the entity.
+               Set_Homonym (H, Homonym (Typ));
+            end if;
 
-                  declare
-                     Candidate : constant Entity_Id :=
-                                   Current_Entity_In_Scope (E);
-                     Decl      : constant Node_Id :=
-                                   Unit_Declaration_Node (Candidate);
+            Insert_Before (Typ_Decl, Decl);
+            Analyze (Decl);
+            Set_Full_View (Inc_T, Typ);
 
-                  begin
-                     if Is_Overloadable (Candidate)
-                       and then Ekind (Candidate) = Ekind (E)
-                       and then Nkind (Decl) = N_Subprogram_Body
-                       and then Acts_As_Spec (Decl)
-                     then
-                        Check_Type_Conformant (Candidate, E);
+            if Is_Tagged then
 
-                     else
-                        Missing_Body;
-                     end if;
-                  end;
+               --  Create a common class-wide type for both views, and set the
+               --  Etype of the class-wide type to the full view.
 
-               else
-                  Missing_Body;
-               end if;
+               Make_Class_Wide_Type (Inc_T);
+               Set_Class_Wide_Type (Typ, Class_Wide_Type (Inc_T));
+               Set_Etype (Class_Wide_Type (Typ), Typ);
             end if;
          end if;
-      end Post_Error;
+      end Build_Incomplete_Type_Declaration;
 
-   --  Start of processing for Check_Completion
+      ------------------
+      -- Designates_T --
+      ------------------
 
-   begin
-      E := First_Entity (Current_Scope);
-      while Present (E) loop
-         if Is_Intrinsic_Subprogram (E) then
-            null;
+      function Designates_T (Subt : Node_Id) return Boolean is
+         Type_Id : constant Name_Id := Chars (Typ);
 
-         --  The following situation requires special handling: a child unit
-         --  that appears in the context clause of the body of its parent:
+         function Names_T (Nam : Node_Id) return Boolean;
+         --  The record type has not been introduced in the current scope
+         --  yet, so we must examine the name of the type itself, either
+         --  an identifier T, or an expanded name of the form P.T, where
+         --  P denotes the current scope.
 
-         --    procedure Parent.Child (...);
+         -------------
+         -- Names_T --
+         -------------
 
-         --    with Parent.Child;
-         --    package body Parent is
+         function Names_T (Nam : Node_Id) return Boolean is
+         begin
+            if Nkind (Nam) = N_Identifier then
+               return Chars (Nam) = Type_Id;
 
-         --  Here Parent.Child appears as a local entity, but should not be
-         --  flagged as requiring completion, because it is a compilation
-         --  unit.
+            elsif Nkind (Nam) = N_Selected_Component then
+               if Chars (Selector_Name (Nam)) = Type_Id then
+                  if Nkind (Prefix (Nam)) = N_Identifier then
+                     return Chars (Prefix (Nam)) = Chars (Current_Scope);
 
-         --  Ignore missing completion for a subprogram that does not come from
-         --  source (including the _Call primitive operation of RAS types,
-         --  which has to have the flag Comes_From_Source for other purposes):
-         --  we assume that the expander will provide the missing completion.
-         --  In case of previous errors, other expansion actions that provide
-         --  bodies for null procedures with not be invoked, so inhibit message
-         --  in those cases.
+                  elsif Nkind (Prefix (Nam)) = N_Selected_Component then
+                     return Chars (Selector_Name (Prefix (Nam))) =
+                            Chars (Current_Scope);
+                  else
+                     return False;
+                  end if;
 
-         --  Note that E_Operator is not in the list that follows, because
-         --  this kind is reserved for predefined operators, that are
-         --  intrinsic and do not need completion.
+               else
+                  return False;
+               end if;
 
-         elsif     Ekind (E) = E_Function
-           or else Ekind (E) = E_Procedure
-           or else Ekind (E) = E_Generic_Function
-           or else Ekind (E) = E_Generic_Procedure
-         then
-            if Has_Completion (E) then
-               null;
+            else
+               return False;
+            end if;
+         end Names_T;
 
-            elsif Is_Subprogram (E) and then Is_Abstract_Subprogram (E) then
-               null;
+      --  Start of processing for Designates_T
 
-            elsif Is_Subprogram (E)
-              and then (not Comes_From_Source (E)
-                         or else Chars (E) = Name_uCall)
-            then
-               null;
+      begin
+         if Nkind (Subt) = N_Identifier then
+            return Chars (Subt) = Type_Id;
 
-            elsif
-               Nkind (Parent (Unit_Declaration_Node (E))) = N_Compilation_Unit
-            then
-               null;
+            --  Reference can be through an expanded name which has not been
+            --  analyzed yet, and which designates enclosing scopes.
 
-            elsif Nkind (Parent (E)) = N_Procedure_Specification
-              and then Null_Present (Parent (E))
-              and then Serious_Errors_Detected > 0
-            then
-               null;
+         elsif Nkind (Subt) = N_Selected_Component then
+            if Names_T (Subt) then
+               return True;
+
+            --  Otherwise it must denote an entity that is already visible.
+            --  The access definition may name a subtype of the enclosing
+            --  type, if there is a previous incomplete declaration for it.
 
             else
-               Post_Error;
+               Find_Selected_Component (Subt);
+               return
+                 Is_Entity_Name (Subt)
+                   and then Scope (Entity (Subt)) = Current_Scope
+                   and then
+                     (Chars (Base_Type (Entity (Subt))) = Type_Id
+                       or else
+                         (Is_Class_Wide_Type (Entity (Subt))
+                           and then
+                             Chars (Etype (Base_Type (Entity (Subt)))) =
+                                                                  Type_Id));
             end if;
 
-         elsif Is_Entry (E) then
-            if not Has_Completion (E) and then
-              (Ekind (Scope (E)) = E_Protected_Object
-                or else Ekind (Scope (E)) = E_Protected_Type)
-            then
-               Post_Error;
-            end if;
+         --  A reference to the current type may appear as the prefix of
+         --  a 'Class attribute.
 
-         elsif Is_Package_Or_Generic_Package (E) then
-            if Unit_Requires_Body (E) then
-               if not Has_Completion (E)
-                 and then Nkind (Parent (Unit_Declaration_Node (E))) /=
-                                                       N_Compilation_Unit
-               then
-                  Post_Error;
-               end if;
+         elsif Nkind (Subt) = N_Attribute_Reference
+           and then Attribute_Name (Subt) = Name_Class
+         then
+            return Names_T (Prefix (Subt));
 
-            elsif not Is_Child_Unit (E) then
-               May_Need_Implicit_Body (E);
-            end if;
+         else
+            return False;
+         end if;
+      end Designates_T;
 
-         --  A formal incomplete type (Ada 2012) does not require a completion;
-         --  other incomplete type declarations do.
+      ----------------
+      -- Mentions_T --
+      ----------------
 
-         elsif Ekind (E) = E_Incomplete_Type
-           and then No (Underlying_Type (E))
-           and then not Is_Generic_Type (E)
-         then
-            Post_Error;
+      function Mentions_T (Acc_Def : Node_Id) return Boolean is
+         Param_Spec : Node_Id;
 
-         elsif (Ekind (E) = E_Task_Type or else
-                Ekind (E) = E_Protected_Type)
-           and then not Has_Completion (E)
-         then
-            Post_Error;
+         Acc_Subprg : constant Node_Id :=
+                        Access_To_Subprogram_Definition (Acc_Def);
 
-         --  A single task declared in the current scope is a constant, verify
-         --  that the body of its anonymous type is in the same scope. If the
-         --  task is defined elsewhere, this may be a renaming declaration for
-         --  which no completion is needed.
+      begin
+         if No (Acc_Subprg) then
+            return Designates_T (Subtype_Mark (Acc_Def));
+         end if;
 
-         elsif Ekind (E) = E_Constant
-           and then Ekind (Etype (E)) = E_Task_Type
-           and then not Has_Completion (Etype (E))
-           and then Scope (Etype (E)) = Current_Scope
-         then
-            Post_Error;
+         --  Component is an access_to_subprogram: examine its formals,
+         --  and result definition in the case of an access_to_function.
 
-         elsif Ekind (E) = E_Protected_Object
-           and then not Has_Completion (Etype (E))
-         then
-            Post_Error;
+         Param_Spec := First (Parameter_Specifications (Acc_Subprg));
+         while Present (Param_Spec) loop
+            if Nkind (Parameter_Type (Param_Spec)) = N_Access_Definition
+              and then Mentions_T (Parameter_Type (Param_Spec))
+            then
+               return True;
 
-         elsif Ekind (E) = E_Record_Type then
-            if Is_Tagged_Type (E) then
-               Check_Abstract_Overriding (E);
-               Check_Conventions (E);
+            elsif Designates_T (Parameter_Type (Param_Spec)) then
+               return True;
             end if;
 
-            Check_Aliased_Component_Types (E);
-
-         elsif Ekind (E) = E_Array_Type then
-            Check_Aliased_Component_Types (E);
+            Next (Param_Spec);
+         end loop;
 
+         if Nkind (Acc_Subprg) = N_Access_Function_Definition then
+            if Nkind (Result_Definition (Acc_Subprg)) =
+                 N_Access_Definition
+            then
+               return Mentions_T (Result_Definition (Acc_Subprg));
+            else
+               return Designates_T (Result_Definition (Acc_Subprg));
+            end if;
          end if;
 
-         Next_Entity (E);
-      end loop;
-   end Check_Completion;
-
-   ------------------------------------
-   -- Check_CPP_Type_Has_No_Defaults --
-   ------------------------------------
+         return False;
+      end Mentions_T;
 
-   procedure Check_CPP_Type_Has_No_Defaults (T : Entity_Id) is
-      Tdef  : constant Node_Id := Type_Definition (Declaration_Node (T));
-      Clist : Node_Id;
-      Comp  : Node_Id;
+   --  Start of processing for Check_Anonymous_Access_Components
 
    begin
-      --  Obtain the component list
-
-      if Nkind (Tdef) = N_Record_Definition then
-         Clist := Component_List (Tdef);
-      else pragma Assert (Nkind (Tdef) = N_Derived_Type_Definition);
-         Clist := Component_List (Record_Extension_Part (Tdef));
+      if No (Comp_List) then
+         return;
       end if;
 
-      --  Check all components to ensure no default expressions
-
-      if Present (Clist) then
-         Comp := First (Component_Items (Clist));
-         while Present (Comp) loop
-            if Present (Expression (Comp)) then
-               Error_Msg_N
-                 ("component of imported 'C'P'P type cannot have "
-                  & "default expression", Expression (Comp));
-            end if;
-
-            Next (Comp);
-         end loop;
-      end if;
-   end Check_CPP_Type_Has_No_Defaults;
+      Comp := First (Component_Items (Comp_List));
+      while Present (Comp) loop
+         if Nkind (Comp) = N_Component_Declaration
+           and then Present
+             (Access_Definition (Component_Definition (Comp)))
+           and then
+             Mentions_T (Access_Definition (Component_Definition (Comp)))
+         then
+            Comp_Def := Component_Definition (Comp);
+            Acc_Def :=
+              Access_To_Subprogram_Definition (Access_Definition (Comp_Def));
 
-   ----------------------------
-   -- Check_Delta_Expression --
-   ----------------------------
+            Build_Incomplete_Type_Declaration;
+            Anon_Access := Make_Temporary (Loc, 'S');
 
-   procedure Check_Delta_Expression (E : Node_Id) is
-   begin
-      if not (Is_Real_Type (Etype (E))) then
-         Wrong_Type (E, Any_Real);
+            --  Create a declaration for the anonymous access type: either
+            --  an access_to_object or an access_to_subprogram.
 
-      elsif not Is_OK_Static_Expression (E) then
-         Flag_Non_Static_Expr
-           ("non-static expression used for delta value!", E);
+            if Present (Acc_Def) then
+               if Nkind (Acc_Def) = N_Access_Function_Definition then
+                  Type_Def :=
+                    Make_Access_Function_Definition (Loc,
+                      Parameter_Specifications =>
+                        Parameter_Specifications (Acc_Def),
+                      Result_Definition        => Result_Definition (Acc_Def));
+               else
+                  Type_Def :=
+                    Make_Access_Procedure_Definition (Loc,
+                      Parameter_Specifications =>
+                        Parameter_Specifications (Acc_Def));
+               end if;
 
-      elsif not UR_Is_Positive (Expr_Value_R (E)) then
-         Error_Msg_N ("delta expression must be positive", E);
+            else
+               Type_Def :=
+                 Make_Access_To_Object_Definition (Loc,
+                   Subtype_Indication =>
+                      Relocate_Node
+                        (Subtype_Mark (Access_Definition (Comp_Def))));
 
-      else
-         return;
-      end if;
+               Set_Constant_Present
+                 (Type_Def, Constant_Present (Access_Definition (Comp_Def)));
+               Set_All_Present
+                 (Type_Def, All_Present (Access_Definition (Comp_Def)));
+            end if;
 
-      --  If any of above errors occurred, then replace the incorrect
-      --  expression by the real 0.1, which should prevent further errors.
+            Set_Null_Exclusion_Present
+              (Type_Def,
+               Null_Exclusion_Present (Access_Definition (Comp_Def)));
 
-      Rewrite (E,
-        Make_Real_Literal (Sloc (E), Ureal_Tenth));
-      Analyze_And_Resolve (E, Standard_Float);
-   end Check_Delta_Expression;
+            Decl :=
+              Make_Full_Type_Declaration (Loc,
+                Defining_Identifier => Anon_Access,
+                Type_Definition     => Type_Def);
 
-   -----------------------------
-   -- Check_Digits_Expression --
-   -----------------------------
+            Insert_Before (Typ_Decl, Decl);
+            Analyze (Decl);
 
-   procedure Check_Digits_Expression (E : Node_Id) is
-   begin
-      if not (Is_Integer_Type (Etype (E))) then
-         Wrong_Type (E, Any_Integer);
+            --  If an access to subprogram, create the extra formals
 
-      elsif not Is_OK_Static_Expression (E) then
-         Flag_Non_Static_Expr
-           ("non-static expression used for digits value!", E);
+            if Present (Acc_Def) then
+               Create_Extra_Formals (Designated_Type (Anon_Access));
 
-      elsif Expr_Value (E) <= 0 then
-         Error_Msg_N ("digits value must be greater than zero", E);
+            --  If an access to object, preserve entity of designated type,
+            --  for ASIS use, before rewriting the component definition.
 
-      else
-         return;
-      end if;
+            else
+               declare
+                  Desig : Entity_Id;
 
-      --  If any of above errors occurred, then replace the incorrect
-      --  expression by the integer 1, which should prevent further errors.
+               begin
+                  Desig := Entity (Subtype_Indication (Type_Def));
 
-      Rewrite (E, Make_Integer_Literal (Sloc (E), 1));
-      Analyze_And_Resolve (E, Standard_Integer);
+                  --  If the access definition is to the current  record,
+                  --  the visible entity at this point is an  incomplete
+                  --  type. Retrieve the full view to simplify  ASIS queries
 
-   end Check_Digits_Expression;
+                  if Ekind (Desig) = E_Incomplete_Type then
+                     Desig := Full_View (Desig);
+                  end if;
 
-   --------------------------
-   -- Check_Initialization --
-   --------------------------
+                  Set_Entity
+                    (Subtype_Mark (Access_Definition  (Comp_Def)), Desig);
+               end;
+            end if;
 
-   procedure Check_Initialization (T : Entity_Id; Exp : Node_Id) is
-   begin
-      --  Special processing for limited types
+            Rewrite (Comp_Def,
+              Make_Component_Definition (Loc,
+                Subtype_Indication =>
+               New_Occurrence_Of (Anon_Access, Loc)));
 
-      if Is_Limited_Type (T)
-        and then not In_Instance
-        and then not In_Inlined_Body
-      then
-         if not OK_For_Limited_Init (T, Exp) then
+            if Ekind (Designated_Type (Anon_Access)) = E_Subprogram_Type then
+               Set_Ekind (Anon_Access, E_Anonymous_Access_Subprogram_Type);
+            else
+               Set_Ekind (Anon_Access, E_Anonymous_Access_Type);
+            end if;
 
-            --  In GNAT mode, this is just a warning, to allow it to be evilly
-            --  turned off. Otherwise it is a real error.
+            Set_Is_Local_Anonymous_Access (Anon_Access);
+         end if;
 
-            if GNAT_Mode then
-               Error_Msg_N
-                 ("??cannot initialize entities of limited type!", Exp);
+         Next (Comp);
+      end loop;
 
-            elsif Ada_Version < Ada_2005 then
+      if Present (Variant_Part (Comp_List)) then
+         declare
+            V : Node_Id;
+         begin
+            V := First_Non_Pragma (Variants (Variant_Part (Comp_List)));
+            while Present (V) loop
+               Check_Anonymous_Access_Components
+                 (Typ_Decl, Typ, Prev, Component_List (V));
+               Next_Non_Pragma (V);
+            end loop;
+         end;
+      end if;
+   end Check_Anonymous_Access_Components;
 
-               --  The side effect removal machinery may generate illegal Ada
-               --  code to avoid the usage of access types and 'reference in
-               --  SPARK mode. Since this is legal code with respect to theorem
-               --  proving, do not emit the error.
+   ----------------------
+   -- Check_Completion --
+   ----------------------
 
-               if GNATprove_Mode
-                 and then Nkind (Exp) = N_Function_Call
-                 and then Nkind (Parent (Exp)) = N_Object_Declaration
-                 and then not Comes_From_Source
-                                (Defining_Identifier (Parent (Exp)))
-               then
-                  null;
+   procedure Check_Completion (Body_Id : Node_Id := Empty) is
+      E : Entity_Id;
 
-               else
-                  Error_Msg_N
-                    ("cannot initialize entities of limited type", Exp);
-                  Explain_Limited_Type (T, Exp);
-               end if;
+      procedure Post_Error;
+      --  Post error message for lack of completion for entity E
 
-            else
-               --  Specialize error message according to kind of illegal
-               --  initial expression.
+      ----------------
+      -- Post_Error --
+      ----------------
 
-               if Nkind (Exp) = N_Type_Conversion
-                 and then Nkind (Expression (Exp)) = N_Function_Call
-               then
-                  Error_Msg_N
-                    ("illegal context for call"
-                      & " to function with limited result", Exp);
+      procedure Post_Error is
 
-               else
-                  Error_Msg_N
-                    ("initialization of limited object requires aggregate "
-                      & "or function call",  Exp);
-               end if;
-            end if;
-         end if;
-      end if;
+         procedure Missing_Body;
+         --  Output missing body message
 
-      --  In gnatc or gnatprove mode, make sure set Do_Range_Check flag gets
-      --  set unless we can be sure that no range check is required.
+         ------------------
+         -- Missing_Body --
+         ------------------
 
-      if (GNATprove_Mode or not Expander_Active)
-        and then Is_Scalar_Type (T)
-        and then not Is_In_Range (Exp, T, Assume_Valid => True)
-      then
-         Set_Do_Range_Check (Exp);
-      end if;
-   end Check_Initialization;
+         procedure Missing_Body is
+         begin
+            --  Spec is in same unit, so we can post on spec
 
-   ----------------------
-   -- Check_Interfaces --
-   ----------------------
+            if In_Same_Source_Unit (Body_Id, E) then
+               Error_Msg_N ("missing body for &", E);
 
-   procedure Check_Interfaces (N : Node_Id; Def : Node_Id) is
-      Parent_Type : constant Entity_Id := Etype (Defining_Identifier (N));
+            --  Spec is in a separate unit, so we have to post on the body
 
-      Iface       : Node_Id;
-      Iface_Def   : Node_Id;
-      Iface_Typ   : Entity_Id;
-      Parent_Node : Node_Id;
+            else
+               Error_Msg_NE ("missing body for & declared#!", Body_Id, E);
+            end if;
+         end Missing_Body;
 
-      Is_Task : Boolean := False;
-      --  Set True if parent type or any progenitor is a task interface
+      --  Start of processing for Post_Error
 
-      Is_Protected : Boolean := False;
-      --  Set True if parent type or any progenitor is a protected interface
+      begin
+         if not Comes_From_Source (E) then
 
-      procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id);
-      --  Check that a progenitor is compatible with declaration.
-      --  Error is posted on Error_Node.
+            if Ekind_In (E, E_Task_Type, E_Protected_Type) then
 
-      ------------------
-      -- Check_Ifaces --
-      ------------------
+               --  It may be an anonymous protected type created for a
+               --  single variable. Post error on variable, if present.
 
-      procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id) is
-         Iface_Id : constant Entity_Id :=
-                      Defining_Identifier (Parent (Iface_Def));
-         Type_Def : Node_Id;
+               declare
+                  Var : Entity_Id;
 
-      begin
-         if Nkind (N) = N_Private_Extension_Declaration then
-            Type_Def := N;
-         else
-            Type_Def := Type_Definition (N);
-         end if;
+               begin
+                  Var := First_Entity (Current_Scope);
+                  while Present (Var) loop
+                     exit when Etype (Var) = E
+                       and then Comes_From_Source (Var);
 
-         if Is_Task_Interface (Iface_Id) then
-            Is_Task := True;
+                     Next_Entity (Var);
+                  end loop;
 
-         elsif Is_Protected_Interface (Iface_Id) then
-            Is_Protected := True;
+                  if Present (Var) then
+                     E := Var;
+                  end if;
+               end;
+            end if;
          end if;
 
-         if Is_Synchronized_Interface (Iface_Id) then
+         --  If a generated entity has no completion, then either previous
+         --  semantic errors have disabled the expansion phase, or else we had
+         --  missing subunits, or else we are compiling without expansion,
+         --  or else something is very wrong.
 
-            --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
-            --  extension derived from a synchronized interface must explicitly
-            --  be declared synchronized, because the full view will be a
-            --  synchronized type.
+         if not Comes_From_Source (E) then
+            pragma Assert
+              (Serious_Errors_Detected > 0
+                or else Configurable_Run_Time_Violations > 0
+                or else Subunits_Missing
+                or else not Expander_Active);
+            return;
 
-            if Nkind (N) = N_Private_Extension_Declaration then
-               if not Synchronized_Present (N) then
+         --  Here for source entity
+
+         else
+            --  Here if no body to post the error message, so we post the error
+            --  on the declaration that has no completion. This is not really
+            --  the right place to post it, think about this later ???
+
+            if No (Body_Id) then
+               if Is_Type (E) then
                   Error_Msg_NE
-                    ("private extension of& must be explicitly synchronized",
-                      N, Iface_Id);
+                    ("missing full declaration for }", Parent (E), E);
+               else
+                  Error_Msg_NE ("missing body for &", Parent (E), E);
                end if;
 
-            --  However, by 3.9.4(16/2), a full type that is a record extension
-            --  is never allowed to derive from a synchronized interface (note
-            --  that interfaces must be excluded from this check, because those
-            --  are represented by derived type definitions in some cases).
+            --  Package body has no completion for a declaration that appears
+            --  in the corresponding spec. Post error on the body, with a
+            --  reference to the non-completed declaration.
 
-            elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition
-              and then not Interface_Present (Type_Definition (N))
-            then
-               Error_Msg_N ("record extension cannot derive from synchronized"
-                             & " interface", Error_Node);
-            end if;
-         end if;
+            else
+               Error_Msg_Sloc := Sloc (E);
 
-         --  Check that the characteristics of the progenitor are compatible
-         --  with the explicit qualifier in the declaration.
-         --  The check only applies to qualifiers that come from source.
-         --  Limited_Present also appears in the declaration of corresponding
-         --  records, and the check does not apply to them.
+               if Is_Type (E) then
+                  Error_Msg_NE ("missing full declaration for }!", Body_Id, E);
 
-         if Limited_Present (Type_Def)
-           and then not
-             Is_Concurrent_Record_Type (Defining_Identifier (N))
-         then
-            if Is_Limited_Interface (Parent_Type)
-              and then not Is_Limited_Interface (Iface_Id)
-            then
-               Error_Msg_NE
-                 ("progenitor& must be limited interface",
-                   Error_Node, Iface_Id);
+               elsif Is_Overloadable (E)
+                 and then Current_Entity_In_Scope (E) /= E
+               then
+                  --  It may be that the completion is mistyped and appears as
+                  --  a distinct overloading of the entity.
 
-            elsif
-              (Task_Present (Iface_Def)
-                or else Protected_Present (Iface_Def)
-                or else Synchronized_Present (Iface_Def))
-              and then Nkind (N) /= N_Private_Extension_Declaration
-              and then not Error_Posted (N)
-            then
-               Error_Msg_NE
-                 ("progenitor& must be limited interface",
-                   Error_Node, Iface_Id);
+                  declare
+                     Candidate : constant Entity_Id :=
+                                   Current_Entity_In_Scope (E);
+                     Decl      : constant Node_Id :=
+                                   Unit_Declaration_Node (Candidate);
+
+                  begin
+                     if Is_Overloadable (Candidate)
+                       and then Ekind (Candidate) = Ekind (E)
+                       and then Nkind (Decl) = N_Subprogram_Body
+                       and then Acts_As_Spec (Decl)
+                     then
+                        Check_Type_Conformant (Candidate, E);
+
+                     else
+                        Missing_Body;
+                     end if;
+                  end;
+
+               else
+                  Missing_Body;
+               end if;
             end if;
+         end if;
+      end Post_Error;
 
-         --  Protected interfaces can only inherit from limited, synchronized
-         --  or protected interfaces.
+      --  Local variables
 
-         elsif Nkind (N) = N_Full_Type_Declaration
-           and then  Protected_Present (Type_Def)
-         then
-            if Limited_Present (Iface_Def)
-              or else Synchronized_Present (Iface_Def)
-              or else Protected_Present (Iface_Def)
-            then
-               null;
+      Pack_Id : constant Entity_Id := Current_Scope;
 
-            elsif Task_Present (Iface_Def) then
-               Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
-                            & " from task interface", Error_Node);
+   --  Start of processing for Check_Completion
 
-            else
-               Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
-                            & " from non-limited interface", Error_Node);
-            end if;
+   begin
+      E := First_Entity (Pack_Id);
+      while Present (E) loop
+         if Is_Intrinsic_Subprogram (E) then
+            null;
 
-         --  Ada 2005 (AI-345): Synchronized interfaces can only inherit from
-         --  limited and synchronized.
+         --  The following situation requires special handling: a child unit
+         --  that appears in the context clause of the body of its parent:
 
-         elsif Synchronized_Present (Type_Def) then
-            if Limited_Present (Iface_Def)
-              or else Synchronized_Present (Iface_Def)
-            then
-               null;
+         --    procedure Parent.Child (...);
 
-            elsif Protected_Present (Iface_Def)
-              and then Nkind (N) /= N_Private_Extension_Declaration
-            then
-               Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
-                            & " from protected interface", Error_Node);
+         --    with Parent.Child;
+         --    package body Parent is
 
-            elsif Task_Present (Iface_Def)
-              and then Nkind (N) /= N_Private_Extension_Declaration
-            then
-               Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
-                            & " from task interface", Error_Node);
+         --  Here Parent.Child appears as a local entity, but should not be
+         --  flagged as requiring completion, because it is a compilation
+         --  unit.
 
-            elsif not Is_Limited_Interface (Iface_Id) then
-               Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
-                            & " from non-limited interface", Error_Node);
-            end if;
+         --  Ignore missing completion for a subprogram that does not come from
+         --  source (including the _Call primitive operation of RAS types,
+         --  which has to have the flag Comes_From_Source for other purposes):
+         --  we assume that the expander will provide the missing completion.
+         --  In case of previous errors, other expansion actions that provide
+         --  bodies for null procedures with not be invoked, so inhibit message
+         --  in those cases.
 
-         --  Ada 2005 (AI-345): Task interfaces can only inherit from limited,
-         --  synchronized or task interfaces.
+         --  Note that E_Operator is not in the list that follows, because
+         --  this kind is reserved for predefined operators, that are
+         --  intrinsic and do not need completion.
 
-         elsif Nkind (N) = N_Full_Type_Declaration
-           and then Task_Present (Type_Def)
+         elsif Ekind_In (E, E_Function,
+                            E_Procedure,
+                            E_Generic_Function,
+                            E_Generic_Procedure)
          then
-            if Limited_Present (Iface_Def)
-              or else Synchronized_Present (Iface_Def)
-              or else Task_Present (Iface_Def)
+            if Has_Completion (E) then
+               null;
+
+            elsif Is_Subprogram (E) and then Is_Abstract_Subprogram (E) then
+               null;
+
+            elsif Is_Subprogram (E)
+              and then (not Comes_From_Source (E)
+                         or else Chars (E) = Name_uCall)
             then
                null;
 
-            elsif Protected_Present (Iface_Def) then
-               Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
-                            & " protected interface", Error_Node);
+            elsif
+               Nkind (Parent (Unit_Declaration_Node (E))) = N_Compilation_Unit
+            then
+               null;
+
+            elsif Nkind (Parent (E)) = N_Procedure_Specification
+              and then Null_Present (Parent (E))
+              and then Serious_Errors_Detected > 0
+            then
+               null;
 
             else
-               Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
-                            & " non-limited interface", Error_Node);
+               Post_Error;
             end if;
-         end if;
-      end Check_Ifaces;
 
-   --  Start of processing for Check_Interfaces
-
-   begin
-      if Is_Interface (Parent_Type) then
-         if Is_Task_Interface (Parent_Type) then
-            Is_Task := True;
+         elsif Is_Entry (E) then
+            if not Has_Completion (E) and then
+              (Ekind (Scope (E)) = E_Protected_Object
+                or else Ekind (Scope (E)) = E_Protected_Type)
+            then
+               Post_Error;
+            end if;
 
-         elsif Is_Protected_Interface (Parent_Type) then
-            Is_Protected := True;
-         end if;
-      end if;
+         elsif Is_Package_Or_Generic_Package (E) then
+            if Unit_Requires_Body (E) then
+               if not Has_Completion (E)
+                 and then Nkind (Parent (Unit_Declaration_Node (E))) /=
+                                                       N_Compilation_Unit
+               then
+                  Post_Error;
+               end if;
 
-      if Nkind (N) = N_Private_Extension_Declaration then
+            elsif not Is_Child_Unit (E) then
+               May_Need_Implicit_Body (E);
+            end if;
 
-         --  Check that progenitors are compatible with declaration
+         --  A formal incomplete type (Ada 2012) does not require a completion;
+         --  other incomplete type declarations do.
 
-         Iface := First (Interface_List (Def));
-         while Present (Iface) loop
-            Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
+         elsif Ekind (E) = E_Incomplete_Type
+           and then No (Underlying_Type (E))
+           and then not Is_Generic_Type (E)
+         then
+            Post_Error;
 
-            Parent_Node := Parent (Base_Type (Iface_Typ));
-            Iface_Def   := Type_Definition (Parent_Node);
+         elsif Ekind_In (E, E_Task_Type, E_Protected_Type)
+           and then not Has_Completion (E)
+         then
+            Post_Error;
 
-            if not Is_Interface (Iface_Typ) then
-               Diagnose_Interface (Iface, Iface_Typ);
+         --  A single task declared in the current scope is a constant, verify
+         --  that the body of its anonymous type is in the same scope. If the
+         --  task is defined elsewhere, this may be a renaming declaration for
+         --  which no completion is needed.
 
-            else
-               Check_Ifaces (Iface_Def, Iface);
-            end if;
-
-            Next (Iface);
-         end loop;
-
-         if Is_Task and Is_Protected then
-            Error_Msg_N
-              ("type cannot derive from task and protected interface", N);
-         end if;
-
-         return;
-      end if;
-
-      --  Full type declaration of derived type.
-      --  Check compatibility with parent if it is interface type
-
-      if Nkind (Type_Definition (N)) = N_Derived_Type_Definition
-        and then Is_Interface (Parent_Type)
-      then
-         Parent_Node := Parent (Parent_Type);
-
-         --  More detailed checks for interface varieties
-
-         Check_Ifaces
-           (Iface_Def  => Type_Definition (Parent_Node),
-            Error_Node => Subtype_Indication (Type_Definition (N)));
-      end if;
+         elsif Ekind (E) = E_Constant
+           and then Ekind (Etype (E)) = E_Task_Type
+           and then not Has_Completion (Etype (E))
+           and then Scope (Etype (E)) = Current_Scope
+         then
+            Post_Error;
 
-      Iface := First (Interface_List (Def));
-      while Present (Iface) loop
-         Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
+         elsif Ekind (E) = E_Protected_Object
+           and then not Has_Completion (Etype (E))
+         then
+            Post_Error;
 
-         Parent_Node := Parent (Base_Type (Iface_Typ));
-         Iface_Def   := Type_Definition (Parent_Node);
+         elsif Ekind (E) = E_Record_Type then
+            if Is_Tagged_Type (E) then
+               Check_Abstract_Overriding (E);
+               Check_Conventions (E);
+            end if;
 
-         if not Is_Interface (Iface_Typ) then
-            Diagnose_Interface (Iface, Iface_Typ);
+            Check_Aliased_Component_Types (E);
 
-         else
-            --  "The declaration of a specific descendant of an interface
-            --   type freezes the interface type" RM 13.14
+         elsif Ekind (E) = E_Array_Type then
+            Check_Aliased_Component_Types (E);
 
-            Freeze_Before (N, Iface_Typ);
-            Check_Ifaces (Iface_Def, Error_Node => Iface);
          end if;
 
-         Next (Iface);
+         Next_Entity (E);
       end loop;
-
-      if Is_Task and Is_Protected then
-         Error_Msg_N
-           ("type cannot derive from task and protected interface", N);
-      end if;
-   end Check_Interfaces;
+   end Check_Completion;
 
    ------------------------------------
-   -- Check_Or_Process_Discriminants --
+   -- Check_CPP_Type_Has_No_Defaults --
    ------------------------------------
 
-   --  If an incomplete or private type declaration was already given for the
-   --  type, the discriminants may have already been processed if they were
-   --  present on the incomplete declaration. In this case a full conformance
-   --  check has been performed in Find_Type_Name, and we then recheck here
-   --  some properties that can't be checked on the partial view alone.
-   --  Otherwise we call Process_Discriminants.
+   procedure Check_CPP_Type_Has_No_Defaults (T : Entity_Id) is
+      Tdef  : constant Node_Id := Type_Definition (Declaration_Node (T));
+      Clist : Node_Id;
+      Comp  : Node_Id;
 
-   procedure Check_Or_Process_Discriminants
-     (N    : Node_Id;
-      T    : Entity_Id;
-      Prev : Entity_Id := Empty)
-   is
    begin
-      if Has_Discriminants (T) then
-
-         --  Discriminants are already set on T if they were already present
-         --  on the partial view. Make them visible to component declarations.
-
-         declare
-            D : Entity_Id;
-            --  Discriminant on T (full view) referencing expr on partial view
+      --  Obtain the component list
 
-            Prev_D : Entity_Id;
-            --  Entity of corresponding discriminant on partial view
+      if Nkind (Tdef) = N_Record_Definition then
+         Clist := Component_List (Tdef);
+      else pragma Assert (Nkind (Tdef) = N_Derived_Type_Definition);
+         Clist := Component_List (Record_Extension_Part (Tdef));
+      end if;
 
-            New_D : Node_Id;
-            --  Discriminant specification for full view, expression is the
-            --  syntactic copy on full view (which has been checked for
-            --  conformance with partial view), only used here to post error
-            --  message.
+      --  Check all components to ensure no default expressions
 
-         begin
-            D     := First_Discriminant (T);
-            New_D := First (Discriminant_Specifications (N));
-            while Present (D) loop
-               Prev_D := Current_Entity (D);
-               Set_Current_Entity (D);
-               Set_Is_Immediately_Visible (D);
-               Set_Homonym (D, Prev_D);
+      if Present (Clist) then
+         Comp := First (Component_Items (Clist));
+         while Present (Comp) loop
+            if Present (Expression (Comp)) then
+               Error_Msg_N
+                 ("component of imported 'C'P'P type cannot have "
+                  & "default expression", Expression (Comp));
+            end if;
 
-               --  Handle the case where there is an untagged partial view and
-               --  the full view is tagged: must disallow discriminants with
-               --  defaults, unless compiling for Ada 2012, which allows a
-               --  limited tagged type to have defaulted discriminants (see
-               --  AI05-0214). However, suppress error here if it was already
-               --  reported on the default expression of the partial view.
+            Next (Comp);
+         end loop;
+      end if;
+   end Check_CPP_Type_Has_No_Defaults;
 
-               if Is_Tagged_Type (T)
-                 and then Present (Expression (Parent (D)))
-                 and then (not Is_Limited_Type (Current_Scope)
-                            or else Ada_Version < Ada_2012)
-                 and then not Error_Posted (Expression (Parent (D)))
-               then
-                  if Ada_Version >= Ada_2012 then
-                     Error_Msg_N
-                       ("discriminants of nonlimited tagged type cannot have"
-                          & " defaults",
-                        Expression (New_D));
-                  else
-                     Error_Msg_N
-                       ("discriminants of tagged type cannot have defaults",
-                        Expression (New_D));
-                  end if;
-               end if;
+   ----------------------------
+   -- Check_Delta_Expression --
+   ----------------------------
 
-               --  Ada 2005 (AI-230): Access discriminant allowed in
-               --  non-limited record types.
+   procedure Check_Delta_Expression (E : Node_Id) is
+   begin
+      if not (Is_Real_Type (Etype (E))) then
+         Wrong_Type (E, Any_Real);
 
-               if Ada_Version < Ada_2005 then
+      elsif not Is_OK_Static_Expression (E) then
+         Flag_Non_Static_Expr
+           ("non-static expression used for delta value!", E);
 
-                  --  This restriction gets applied to the full type here. It
-                  --  has already been applied earlier to the partial view.
+      elsif not UR_Is_Positive (Expr_Value_R (E)) then
+         Error_Msg_N ("delta expression must be positive", E);
 
-                  Check_Access_Discriminant_Requires_Limited (Parent (D), N);
-               end if;
+      else
+         return;
+      end if;
 
-               Next_Discriminant (D);
-               Next (New_D);
-            end loop;
-         end;
+      --  If any of above errors occurred, then replace the incorrect
+      --  expression by the real 0.1, which should prevent further errors.
 
-      elsif Present (Discriminant_Specifications (N)) then
-         Process_Discriminants (N, Prev);
-      end if;
-   end Check_Or_Process_Discriminants;
+      Rewrite (E,
+        Make_Real_Literal (Sloc (E), Ureal_Tenth));
+      Analyze_And_Resolve (E, Standard_Float);
+   end Check_Delta_Expression;
 
-   ----------------------
-   -- Check_Real_Bound --
-   ----------------------
+   -----------------------------
+   -- Check_Digits_Expression --
+   -----------------------------
 
-   procedure Check_Real_Bound (Bound : Node_Id) is
+   procedure Check_Digits_Expression (E : Node_Id) is
    begin
-      if not Is_Real_Type (Etype (Bound)) then
-         Error_Msg_N
-           ("bound in real type definition must be of real type", Bound);
+      if not (Is_Integer_Type (Etype (E))) then
+         Wrong_Type (E, Any_Integer);
 
-      elsif not Is_OK_Static_Expression (Bound) then
+      elsif not Is_OK_Static_Expression (E) then
          Flag_Non_Static_Expr
-           ("non-static expression used for real type bound!", Bound);
+           ("non-static expression used for digits value!", E);
+
+      elsif Expr_Value (E) <= 0 then
+         Error_Msg_N ("digits value must be greater than zero", E);
 
       else
          return;
       end if;
 
-      Rewrite
-        (Bound, Make_Real_Literal (Sloc (Bound), Ureal_0));
-      Analyze (Bound);
-      Resolve (Bound, Standard_Float);
-   end Check_Real_Bound;
+      --  If any of above errors occurred, then replace the incorrect
+      --  expression by the integer 1, which should prevent further errors.
 
-   ------------------------------
-   -- Complete_Private_Subtype --
-   ------------------------------
+      Rewrite (E, Make_Integer_Literal (Sloc (E), 1));
+      Analyze_And_Resolve (E, Standard_Integer);
 
-   procedure Complete_Private_Subtype
-     (Priv        : Entity_Id;
-      Full        : Entity_Id;
-      Full_Base   : Entity_Id;
-      Related_Nod : Node_Id)
-   is
-      Save_Next_Entity : Entity_Id;
-      Save_Homonym     : Entity_Id;
+   end Check_Digits_Expression;
+
+   --------------------------
+   -- Check_Initialization --
+   --------------------------
 
+   procedure Check_Initialization (T : Entity_Id; Exp : Node_Id) is
    begin
-      --  Set semantic attributes for (implicit) private subtype completion.
-      --  If the full type has no discriminants, then it is a copy of the full
-      --  view of the base. Otherwise, it is a subtype of the base with a
-      --  possible discriminant constraint. Save and restore the original
-      --  Next_Entity field of full to ensure that the calls to Copy_Node
-      --  do not corrupt the entity chain.
-
-      --  Note that the type of the full view is the same entity as the type of
-      --  the partial view. In this fashion, the subtype has access to the
-      --  correct view of the parent.
+      --  Special processing for limited types
 
-      Save_Next_Entity := Next_Entity (Full);
-      Save_Homonym     := Homonym (Priv);
+      if Is_Limited_Type (T)
+        and then not In_Instance
+        and then not In_Inlined_Body
+      then
+         if not OK_For_Limited_Init (T, Exp) then
 
-      case Ekind (Full_Base) is
-         when E_Record_Type    |
-              E_Record_Subtype |
-              Class_Wide_Kind  |
-              Private_Kind     |
-              Task_Kind        |
-              Protected_Kind   =>
-            Copy_Node (Priv, Full);
+            --  In GNAT mode, this is just a warning, to allow it to be evilly
+            --  turned off. Otherwise it is a real error.
 
-            Set_Has_Discriminants
-                             (Full, Has_Discriminants (Full_Base));
-            Set_Has_Unknown_Discriminants
-                             (Full, Has_Unknown_Discriminants (Full_Base));
-            Set_First_Entity (Full, First_Entity (Full_Base));
-            Set_Last_Entity  (Full, Last_Entity (Full_Base));
+            if GNAT_Mode then
+               Error_Msg_N
+                 ("??cannot initialize entities of limited type!", Exp);
 
-            --  If the underlying base type is constrained, we know that the
-            --  full view of the subtype is constrained as well (the converse
-            --  is not necessarily true).
+            elsif Ada_Version < Ada_2005 then
 
-            if Is_Constrained (Full_Base) then
-               Set_Is_Constrained (Full);
-            end if;
+               --  The side effect removal machinery may generate illegal Ada
+               --  code to avoid the usage of access types and 'reference in
+               --  SPARK mode. Since this is legal code with respect to theorem
+               --  proving, do not emit the error.
 
-         when others =>
-            Copy_Node (Full_Base, Full);
+               if GNATprove_Mode
+                 and then Nkind (Exp) = N_Function_Call
+                 and then Nkind (Parent (Exp)) = N_Object_Declaration
+                 and then not Comes_From_Source
+                                (Defining_Identifier (Parent (Exp)))
+               then
+                  null;
 
-            Set_Chars         (Full, Chars (Priv));
-            Conditional_Delay (Full, Priv);
-            Set_Sloc          (Full, Sloc (Priv));
-      end case;
+               else
+                  Error_Msg_N
+                    ("cannot initialize entities of limited type", Exp);
+                  Explain_Limited_Type (T, Exp);
+               end if;
 
-      Set_Next_Entity               (Full, Save_Next_Entity);
-      Set_Homonym                   (Full, Save_Homonym);
-      Set_Associated_Node_For_Itype (Full, Related_Nod);
+            else
+               --  Specialize error message according to kind of illegal
+               --  initial expression.
 
-      --  Set common attributes for all subtypes: kind, convention, etc.
+               if Nkind (Exp) = N_Type_Conversion
+                 and then Nkind (Expression (Exp)) = N_Function_Call
+               then
+                  Error_Msg_N
+                    ("illegal context for call"
+                      & " to function with limited result", Exp);
 
-      Set_Ekind (Full, Subtype_Kind (Ekind (Full_Base)));
-      Set_Convention (Full, Convention (Full_Base));
+               else
+                  Error_Msg_N
+                    ("initialization of limited object requires aggregate "
+                      & "or function call",  Exp);
+               end if;
+            end if;
+         end if;
+      end if;
 
-      --  The Etype of the full view is inconsistent. Gigi needs to see the
-      --  structural full view,  which is what the current scheme gives:
-      --  the Etype of the full view is the etype of the full base. However,
-      --  if the full base is a derived type, the full view then looks like
-      --  a subtype of the parent, not a subtype of the full base. If instead
-      --  we write:
+      --  In gnatc or gnatprove mode, make sure set Do_Range_Check flag gets
+      --  set unless we can be sure that no range check is required.
 
-      --       Set_Etype (Full, Full_Base);
+      if (GNATprove_Mode or not Expander_Active)
+        and then Is_Scalar_Type (T)
+        and then not Is_In_Range (Exp, T, Assume_Valid => True)
+      then
+         Set_Do_Range_Check (Exp);
+      end if;
+   end Check_Initialization;
 
-      --  then we get inconsistencies in the front-end (confusion between
-      --  views). Several outstanding bugs are related to this ???
+   ----------------------
+   -- Check_Interfaces --
+   ----------------------
 
-      Set_Is_First_Subtype (Full, False);
-      Set_Scope            (Full, Scope (Priv));
-      Set_Size_Info        (Full, Full_Base);
-      Set_RM_Size          (Full, RM_Size (Full_Base));
-      Set_Is_Itype         (Full);
+   procedure Check_Interfaces (N : Node_Id; Def : Node_Id) is
+      Parent_Type : constant Entity_Id := Etype (Defining_Identifier (N));
 
-      --  A subtype of a private-type-without-discriminants, whose full-view
-      --  has discriminants with default expressions, is not constrained.
+      Iface       : Node_Id;
+      Iface_Def   : Node_Id;
+      Iface_Typ   : Entity_Id;
+      Parent_Node : Node_Id;
 
-      if not Has_Discriminants (Priv) then
-         Set_Is_Constrained (Full, Is_Constrained (Full_Base));
+      Is_Task : Boolean := False;
+      --  Set True if parent type or any progenitor is a task interface
 
-         if Has_Discriminants (Full_Base) then
-            Set_Discriminant_Constraint
-              (Full, Discriminant_Constraint (Full_Base));
+      Is_Protected : Boolean := False;
+      --  Set True if parent type or any progenitor is a protected interface
 
-            --  The partial view may have been indefinite, the full view
-            --  might not be.
+      procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id);
+      --  Check that a progenitor is compatible with declaration. If an error
+      --  message is output, it is posted on Error_Node.
 
-            Set_Has_Unknown_Discriminants
-              (Full, Has_Unknown_Discriminants (Full_Base));
+      ------------------
+      -- Check_Ifaces --
+      ------------------
+
+      procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id) is
+         Iface_Id : constant Entity_Id :=
+                      Defining_Identifier (Parent (Iface_Def));
+         Type_Def : Node_Id;
+
+      begin
+         if Nkind (N) = N_Private_Extension_Declaration then
+            Type_Def := N;
+         else
+            Type_Def := Type_Definition (N);
          end if;
-      end if;
 
-      Set_First_Rep_Item     (Full, First_Rep_Item (Full_Base));
-      Set_Depends_On_Private (Full, Has_Private_Component (Full));
+         if Is_Task_Interface (Iface_Id) then
+            Is_Task := True;
 
-      --  Freeze the private subtype entity if its parent is delayed, and not
-      --  already frozen. We skip this processing if the type is an anonymous
-      --  subtype of a record component, or is the corresponding record of a
-      --  protected type, since ???
+         elsif Is_Protected_Interface (Iface_Id) then
+            Is_Protected := True;
+         end if;
 
-      if not Is_Type (Scope (Full)) then
-         Set_Has_Delayed_Freeze (Full,
-           Has_Delayed_Freeze (Full_Base)
-             and then (not Is_Frozen (Full_Base)));
-      end if;
+         if Is_Synchronized_Interface (Iface_Id) then
 
-      Set_Freeze_Node (Full, Empty);
-      Set_Is_Frozen (Full, False);
-      Set_Full_View (Priv, Full);
+            --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
+            --  extension derived from a synchronized interface must explicitly
+            --  be declared synchronized, because the full view will be a
+            --  synchronized type.
 
-      if Has_Discriminants (Full) then
-         Set_Stored_Constraint_From_Discriminant_Constraint (Full);
-         Set_Stored_Constraint (Priv, Stored_Constraint (Full));
+            if Nkind (N) = N_Private_Extension_Declaration then
+               if not Synchronized_Present (N) then
+                  Error_Msg_NE
+                    ("private extension of& must be explicitly synchronized",
+                      N, Iface_Id);
+               end if;
 
-         if Has_Unknown_Discriminants (Full) then
-            Set_Discriminant_Constraint (Full, No_Elist);
-         end if;
-      end if;
+            --  However, by 3.9.4(16/2), a full type that is a record extension
+            --  is never allowed to derive from a synchronized interface (note
+            --  that interfaces must be excluded from this check, because those
+            --  are represented by derived type definitions in some cases).
 
-      if Ekind (Full_Base) = E_Record_Type
-        and then Has_Discriminants (Full_Base)
-        and then Has_Discriminants (Priv) -- might not, if errors
-        and then not Has_Unknown_Discriminants (Priv)
-        and then not Is_Empty_Elmt_List (Discriminant_Constraint (Priv))
-      then
-         Create_Constrained_Components
-           (Full, Related_Nod, Full_Base, Discriminant_Constraint (Priv));
+            elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition
+              and then not Interface_Present (Type_Definition (N))
+            then
+               Error_Msg_N ("record extension cannot derive from synchronized "
+                            & "interface", Error_Node);
+            end if;
+         end if;
 
-      --  If the full base is itself derived from private, build a congruent
-      --  subtype of its underlying type, for use by the back end. For a
-      --  constrained record component, the declaration cannot be placed on
-      --  the component list, but it must nevertheless be built an analyzed, to
-      --  supply enough information for Gigi to compute the size of component.
+         --  Check that the characteristics of the progenitor are compatible
+         --  with the explicit qualifier in the declaration.
+         --  The check only applies to qualifiers that come from source.
+         --  Limited_Present also appears in the declaration of corresponding
+         --  records, and the check does not apply to them.
 
-      elsif Ekind (Full_Base) in Private_Kind
-        and then Is_Derived_Type (Full_Base)
-        and then Has_Discriminants (Full_Base)
-        and then (Ekind (Current_Scope) /= E_Record_Subtype)
-      then
-         if not Is_Itype (Priv)
-           and then
-             Nkind (Subtype_Indication (Parent (Priv))) = N_Subtype_Indication
+         if Limited_Present (Type_Def)
+           and then not
+             Is_Concurrent_Record_Type (Defining_Identifier (N))
          then
-            Build_Underlying_Full_View
-              (Parent (Priv), Full, Etype (Full_Base));
+            if Is_Limited_Interface (Parent_Type)
+              and then not Is_Limited_Interface (Iface_Id)
+            then
+               Error_Msg_NE
+                 ("progenitor & must be limited interface",
+                   Error_Node, Iface_Id);
 
-         elsif Nkind (Related_Nod) = N_Component_Declaration then
-            Build_Underlying_Full_View (Related_Nod, Full, Etype (Full_Base));
-         end if;
+            elsif
+              (Task_Present (Iface_Def)
+                or else Protected_Present (Iface_Def)
+                or else Synchronized_Present (Iface_Def))
+              and then Nkind (N) /= N_Private_Extension_Declaration
+              and then not Error_Posted (N)
+            then
+               Error_Msg_NE
+                 ("progenitor & must be limited interface",
+                   Error_Node, Iface_Id);
+            end if;
 
-      elsif Is_Record_Type (Full_Base) then
+         --  Protected interfaces can only inherit from limited, synchronized
+         --  or protected interfaces.
 
-         --  Show Full is simply a renaming of Full_Base
+         elsif Nkind (N) = N_Full_Type_Declaration
+           and then  Protected_Present (Type_Def)
+         then
+            if Limited_Present (Iface_Def)
+              or else Synchronized_Present (Iface_Def)
+              or else Protected_Present (Iface_Def)
+            then
+               null;
 
-         Set_Cloned_Subtype (Full, Full_Base);
-      end if;
+            elsif Task_Present (Iface_Def) then
+               Error_Msg_N ("(Ada 2005) protected interface cannot inherit "
+                            & "from task interface", Error_Node);
 
-      --  It is unsafe to share the bounds of a scalar type, because the Itype
-      --  is elaborated on demand, and if a bound is non-static then different
-      --  orders of elaboration in different units will lead to different
-      --  external symbols.
+            else
+               Error_Msg_N ("(Ada 2005) protected interface cannot inherit "
+                            & "from non-limited interface", Error_Node);
+            end if;
 
-      if Is_Scalar_Type (Full_Base) then
-         Set_Scalar_Range (Full,
-           Make_Range (Sloc (Related_Nod),
-             Low_Bound  =>
-               Duplicate_Subexpr_No_Checks (Type_Low_Bound  (Full_Base)),
-             High_Bound =>
-               Duplicate_Subexpr_No_Checks (Type_High_Bound (Full_Base))));
+         --  Ada 2005 (AI-345): Synchronized interfaces can only inherit from
+         --  limited and synchronized.
 
-         --  This completion inherits the bounds of the full parent, but if
-         --  the parent is an unconstrained floating point type, so is the
-         --  completion.
+         elsif Synchronized_Present (Type_Def) then
+            if Limited_Present (Iface_Def)
+              or else Synchronized_Present (Iface_Def)
+            then
+               null;
 
-         if Is_Floating_Point_Type (Full_Base) then
-            Set_Includes_Infinities
-             (Scalar_Range (Full), Has_Infinities (Full_Base));
-         end if;
-      end if;
+            elsif Protected_Present (Iface_Def)
+              and then Nkind (N) /= N_Private_Extension_Declaration
+            then
+               Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit "
+                            & "from protected interface", Error_Node);
 
-      --  ??? It seems that a lot of fields are missing that should be copied
-      --  from Full_Base to Full. Here are some that are introduced in a
-      --  non-disruptive way but a cleanup is necessary.
+            elsif Task_Present (Iface_Def)
+              and then Nkind (N) /= N_Private_Extension_Declaration
+            then
+               Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit "
+                            & "from task interface", Error_Node);
 
-      if Is_Tagged_Type (Full_Base) then
-         Set_Is_Tagged_Type (Full);
-         Set_Direct_Primitive_Operations (Full,
-           Direct_Primitive_Operations (Full_Base));
+            elsif not Is_Limited_Interface (Iface_Id) then
+               Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit "
+                            & "from non-limited interface", Error_Node);
+            end if;
 
-         --  Inherit class_wide type of full_base in case the partial view was
-         --  not tagged. Otherwise it has already been created when the private
-         --  subtype was analyzed.
+         --  Ada 2005 (AI-345): Task interfaces can only inherit from limited,
+         --  synchronized or task interfaces.
 
-         if No (Class_Wide_Type (Full)) then
-            Set_Class_Wide_Type (Full, Class_Wide_Type (Full_Base));
+         elsif Nkind (N) = N_Full_Type_Declaration
+           and then Task_Present (Type_Def)
+         then
+            if Limited_Present (Iface_Def)
+              or else Synchronized_Present (Iface_Def)
+              or else Task_Present (Iface_Def)
+            then
+               null;
+
+            elsif Protected_Present (Iface_Def) then
+               Error_Msg_N ("(Ada 2005) task interface cannot inherit from "
+                            & "protected interface", Error_Node);
+
+            else
+               Error_Msg_N ("(Ada 2005) task interface cannot inherit from "
+                            & "non-limited interface", Error_Node);
+            end if;
          end if;
+      end Check_Ifaces;
 
-      --  If this is a subtype of a protected or task type, constrain its
-      --  corresponding record, unless this is a subtype without constraints,
-      --  i.e. a simple renaming as with an actual subtype in an instance.
+   --  Start of processing for Check_Interfaces
 
-      elsif Is_Concurrent_Type (Full_Base) then
-         if Has_Discriminants (Full)
-           and then Present (Corresponding_Record_Type (Full_Base))
-           and then
-             not Is_Empty_Elmt_List (Discriminant_Constraint (Full))
-         then
-            Set_Corresponding_Record_Type (Full,
-              Constrain_Corresponding_Record
-                (Full, Corresponding_Record_Type (Full_Base), Related_Nod));
+   begin
+      if Is_Interface (Parent_Type) then
+         if Is_Task_Interface (Parent_Type) then
+            Is_Task := True;
 
-         else
-            Set_Corresponding_Record_Type (Full,
-              Corresponding_Record_Type (Full_Base));
+         elsif Is_Protected_Interface (Parent_Type) then
+            Is_Protected := True;
          end if;
       end if;
 
-      --  Link rep item chain, and also setting of Has_Predicates from private
-      --  subtype to full subtype, since we will need these on the full subtype
-      --  to create the predicate function. Note that the full subtype may
-      --  already have rep items, inherited from the full view of the base
-      --  type, so we must be sure not to overwrite these entries.
-
-      declare
-         Append    : Boolean;
-         Item      : Node_Id;
-         Next_Item : Node_Id;
-
-      begin
-         Item := First_Rep_Item (Full);
+      if Nkind (N) = N_Private_Extension_Declaration then
 
-         --  If no existing rep items on full type, we can just link directly
-         --  to the list of items on the private type.
+         --  Check that progenitors are compatible with declaration
 
-         if No (Item) then
-            Set_First_Rep_Item (Full, First_Rep_Item (Priv));
+         Iface := First (Interface_List (Def));
+         while Present (Iface) loop
+            Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
 
-         --  Otherwise, search to the end of items currently linked to the full
-         --  subtype and append the private items to the end. However, if Priv
-         --  and Full already have the same list of rep items, then the append
-         --  is not done, as that would create a circularity.
+            Parent_Node := Parent (Base_Type (Iface_Typ));
+            Iface_Def   := Type_Definition (Parent_Node);
 
-         elsif Item /= First_Rep_Item (Priv) then
-            Append := True;
+            if not Is_Interface (Iface_Typ) then
+               Diagnose_Interface (Iface, Iface_Typ);
+            else
+               Check_Ifaces (Iface_Def, Iface);
+            end if;
 
-            loop
-               Next_Item := Next_Rep_Item (Item);
-               exit when No (Next_Item);
-               Item := Next_Item;
+            Next (Iface);
+         end loop;
 
-               --  If the private view has aspect specifications, the full view
-               --  inherits them. Since these aspects may already have been
-               --  attached to the full view during derivation, do not append
-               --  them if already present.
+         if Is_Task and Is_Protected then
+            Error_Msg_N
+              ("type cannot derive from task and protected interface", N);
+         end if;
 
-               if Item = First_Rep_Item (Priv) then
-                  Append := False;
-                  exit;
-               end if;
-            end loop;
+         return;
+      end if;
 
-            --  And link the private type items at the end of the chain
+      --  Full type declaration of derived type.
+      --  Check compatibility with parent if it is interface type
 
-            if Append then
-               Set_Next_Rep_Item (Item, First_Rep_Item (Priv));
-            end if;
-         end if;
-      end;
+      if Nkind (Type_Definition (N)) = N_Derived_Type_Definition
+        and then Is_Interface (Parent_Type)
+      then
+         Parent_Node := Parent (Parent_Type);
 
-      --  Make sure Has_Predicates is set on full type if it is set on the
-      --  private type. Note that it may already be set on the full type and
-      --  if so, we don't want to unset it.
+         --  More detailed checks for interface varieties
 
-      if Has_Predicates (Priv) then
-         Set_Has_Predicates (Full);
+         Check_Ifaces
+           (Iface_Def  => Type_Definition (Parent_Node),
+            Error_Node => Subtype_Indication (Type_Definition (N)));
       end if;
-   end Complete_Private_Subtype;
 
-   ----------------------------
-   -- Constant_Redeclaration --
-   ----------------------------
+      Iface := First (Interface_List (Def));
+      while Present (Iface) loop
+         Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
 
-   procedure Constant_Redeclaration
-     (Id : Entity_Id;
-      N  : Node_Id;
-      T  : out Entity_Id)
-   is
-      Prev    : constant Entity_Id := Current_Entity_In_Scope (Id);
-      Obj_Def : constant Node_Id := Object_Definition (N);
-      New_T   : Entity_Id;
+         Parent_Node := Parent (Base_Type (Iface_Typ));
+         Iface_Def   := Type_Definition (Parent_Node);
 
-      procedure Check_Possible_Deferred_Completion
-        (Prev_Id      : Entity_Id;
-         Prev_Obj_Def : Node_Id;
-         Curr_Obj_Def : Node_Id);
-      --  Determine whether the two object definitions describe the partial
-      --  and the full view of a constrained deferred constant. Generate
-      --  a subtype for the full view and verify that it statically matches
-      --  the subtype of the partial view.
+         if not Is_Interface (Iface_Typ) then
+            Diagnose_Interface (Iface, Iface_Typ);
 
-      procedure Check_Recursive_Declaration (Typ : Entity_Id);
-      --  If deferred constant is an access type initialized with an allocator,
-      --  check whether there is an illegal recursion in the definition,
-      --  through a default value of some record subcomponent. This is normally
-      --  detected when generating init procs, but requires this additional
-      --  mechanism when expansion is disabled.
+         else
+            --  "The declaration of a specific descendant of an interface
+            --   type freezes the interface type" RM 13.14
 
-      ----------------------------------------
-      -- Check_Possible_Deferred_Completion --
-      ----------------------------------------
+            Freeze_Before (N, Iface_Typ);
+            Check_Ifaces (Iface_Def, Error_Node => Iface);
+         end if;
 
-      procedure Check_Possible_Deferred_Completion
-        (Prev_Id      : Entity_Id;
-         Prev_Obj_Def : Node_Id;
-         Curr_Obj_Def : Node_Id)
-      is
-      begin
-         if Nkind (Prev_Obj_Def) = N_Subtype_Indication
-           and then Present (Constraint (Prev_Obj_Def))
-           and then Nkind (Curr_Obj_Def) = N_Subtype_Indication
-           and then Present (Constraint (Curr_Obj_Def))
-         then
-            declare
-               Loc    : constant Source_Ptr := Sloc (N);
-               Def_Id : constant Entity_Id  := Make_Temporary (Loc, 'S');
-               Decl   : constant Node_Id    :=
-                          Make_Subtype_Declaration (Loc,
-                            Defining_Identifier => Def_Id,
-                            Subtype_Indication  =>
-                              Relocate_Node (Curr_Obj_Def));
+         Next (Iface);
+      end loop;
 
-            begin
-               Insert_Before_And_Analyze (N, Decl);
-               Set_Etype (Id, Def_Id);
+      if Is_Task and Is_Protected then
+         Error_Msg_N
+           ("type cannot derive from task and protected interface", N);
+      end if;
+   end Check_Interfaces;
 
-               if not Subtypes_Statically_Match (Etype (Prev_Id), Def_Id) then
-                  Error_Msg_Sloc := Sloc (Prev_Id);
-                  Error_Msg_N ("subtype does not statically match deferred " &
-                               "declaration#", N);
-               end if;
-            end;
-         end if;
-      end Check_Possible_Deferred_Completion;
+   ------------------------------------
+   -- Check_Or_Process_Discriminants --
+   ------------------------------------
 
-      ---------------------------------
-      -- Check_Recursive_Declaration --
-      ---------------------------------
+   --  If an incomplete or private type declaration was already given for the
+   --  type, the discriminants may have already been processed if they were
+   --  present on the incomplete declaration. In this case a full conformance
+   --  check has been performed in Find_Type_Name, and we then recheck here
+   --  some properties that can't be checked on the partial view alone.
+   --  Otherwise we call Process_Discriminants.
 
-      procedure Check_Recursive_Declaration (Typ : Entity_Id) is
-         Comp : Entity_Id;
+   procedure Check_Or_Process_Discriminants
+     (N    : Node_Id;
+      T    : Entity_Id;
+      Prev : Entity_Id := Empty)
+   is
+   begin
+      if Has_Discriminants (T) then
 
-      begin
-         if Is_Record_Type (Typ) then
-            Comp := First_Component (Typ);
-            while Present (Comp) loop
-               if Comes_From_Source (Comp) then
-                  if Present (Expression (Parent (Comp)))
-                    and then Is_Entity_Name (Expression (Parent (Comp)))
-                    and then Entity (Expression (Parent (Comp))) = Prev
-                  then
-                     Error_Msg_Sloc := Sloc (Parent (Comp));
-                     Error_Msg_NE
-                       ("illegal circularity with declaration for&#",
-                         N, Comp);
-                     return;
+         --  Discriminants are already set on T if they were already present
+         --  on the partial view. Make them visible to component declarations.
 
-                  elsif Is_Record_Type (Etype (Comp)) then
-                     Check_Recursive_Declaration (Etype (Comp));
-                  end if;
-               end if;
+         declare
+            D : Entity_Id;
+            --  Discriminant on T (full view) referencing expr on partial view
 
-               Next_Component (Comp);
-            end loop;
-         end if;
-      end Check_Recursive_Declaration;
+            Prev_D : Entity_Id;
+            --  Entity of corresponding discriminant on partial view
 
-   --  Start of processing for Constant_Redeclaration
+            New_D : Node_Id;
+            --  Discriminant specification for full view, expression is
+            --  the syntactic copy on full view (which has been checked for
+            --  conformance with partial view), only used here to post error
+            --  message.
 
-   begin
-      if Nkind (Parent (Prev)) = N_Object_Declaration then
-         if Nkind (Object_Definition
-                     (Parent (Prev))) = N_Subtype_Indication
-         then
-            --  Find type of new declaration. The constraints of the two
-            --  views must match statically, but there is no point in
-            --  creating an itype for the full view.
+         begin
+            D     := First_Discriminant (T);
+            New_D := First (Discriminant_Specifications (N));
+            while Present (D) loop
+               Prev_D := Current_Entity (D);
+               Set_Current_Entity (D);
+               Set_Is_Immediately_Visible (D);
+               Set_Homonym (D, Prev_D);
 
-            if Nkind (Obj_Def) = N_Subtype_Indication then
-               Find_Type (Subtype_Mark (Obj_Def));
-               New_T := Entity (Subtype_Mark (Obj_Def));
+               --  Handle the case where there is an untagged partial view and
+               --  the full view is tagged: must disallow discriminants with
+               --  defaults, unless compiling for Ada 2012, which allows a
+               --  limited tagged type to have defaulted discriminants (see
+               --  AI05-0214). However, suppress error here if it was already
+               --  reported on the default expression of the partial view.
 
-            else
-               Find_Type (Obj_Def);
-               New_T := Entity (Obj_Def);
-            end if;
+               if Is_Tagged_Type (T)
+                 and then Present (Expression (Parent (D)))
+                 and then (not Is_Limited_Type (Current_Scope)
+                            or else Ada_Version < Ada_2012)
+                 and then not Error_Posted (Expression (Parent (D)))
+               then
+                  if Ada_Version >= Ada_2012 then
+                     Error_Msg_N
+                       ("discriminants of nonlimited tagged type cannot have "
+                        & "defaults",
+                        Expression (New_D));
+                  else
+                     Error_Msg_N
+                       ("discriminants of tagged type cannot have defaults",
+                        Expression (New_D));
+                  end if;
+               end if;
 
-            T := Etype (Prev);
+               --  Ada 2005 (AI-230): Access discriminant allowed in
+               --  non-limited record types.
 
-         else
-            --  The full view may impose a constraint, even if the partial
-            --  view does not, so construct the subtype.
+               if Ada_Version < Ada_2005 then
 
-            New_T := Find_Type_Of_Object (Obj_Def, N);
-            T     := New_T;
-         end if;
+                  --  This restriction gets applied to the full type here. It
+                  --  has already been applied earlier to the partial view.
 
-      else
-         --  Current declaration is illegal, diagnosed below in Enter_Name
+                  Check_Access_Discriminant_Requires_Limited (Parent (D), N);
+               end if;
 
-         T := Empty;
-         New_T := Any_Type;
-      end if;
+               Next_Discriminant (D);
+               Next (New_D);
+            end loop;
+         end;
 
-      --  If previous full declaration or a renaming declaration exists, or if
-      --  a homograph is present, let Enter_Name handle it, either with an
-      --  error or with the removal of an overridden implicit subprogram.
-      --  The previous one is a full declaration if it has an expression
-      --  (which in the case of an aggregate is indicated by the Init flag).
+      elsif Present (Discriminant_Specifications (N)) then
+         Process_Discriminants (N, Prev);
+      end if;
+   end Check_Or_Process_Discriminants;
 
-      if Ekind (Prev) /= E_Constant
-        or else Nkind (Parent (Prev)) = N_Object_Renaming_Declaration
-        or else Present (Expression (Parent (Prev)))
-        or else Has_Init_Expression (Parent (Prev))
-        or else Present (Full_View (Prev))
-      then
-         Enter_Name (Id);
+   ----------------------
+   -- Check_Real_Bound --
+   ----------------------
 
-      --  Verify that types of both declarations match, or else that both types
-      --  are anonymous access types whose designated subtypes statically match
-      --  (as allowed in Ada 2005 by AI-385).
+   procedure Check_Real_Bound (Bound : Node_Id) is
+   begin
+      if not Is_Real_Type (Etype (Bound)) then
+         Error_Msg_N
+           ("bound in real type definition must be of real type", Bound);
 
-      elsif Base_Type (Etype (Prev)) /= Base_Type (New_T)
-        and then
-          (Ekind (Etype (Prev)) /= E_Anonymous_Access_Type
-             or else Ekind (Etype (New_T)) /= E_Anonymous_Access_Type
-             or else Is_Access_Constant (Etype (New_T)) /=
-                     Is_Access_Constant (Etype (Prev))
-             or else Can_Never_Be_Null (Etype (New_T)) /=
-                     Can_Never_Be_Null (Etype (Prev))
-             or else Null_Exclusion_Present (Parent (Prev)) /=
-                     Null_Exclusion_Present (Parent (Id))
-             or else not Subtypes_Statically_Match
-                           (Designated_Type (Etype (Prev)),
-                            Designated_Type (Etype (New_T))))
-      then
-         Error_Msg_Sloc := Sloc (Prev);
-         Error_Msg_N ("type does not match declaration#", N);
-         Set_Full_View (Prev, Id);
-         Set_Etype (Id, Any_Type);
+      elsif not Is_OK_Static_Expression (Bound) then
+         Flag_Non_Static_Expr
+           ("non-static expression used for real type bound!", Bound);
 
-      elsif
-        Null_Exclusion_Present (Parent (Prev))
-          and then not Null_Exclusion_Present (N)
-      then
-         Error_Msg_Sloc := Sloc (Prev);
-         Error_Msg_N ("null-exclusion does not match declaration#", N);
-         Set_Full_View (Prev, Id);
-         Set_Etype (Id, Any_Type);
+      else
+         return;
+      end if;
 
-      --  If so, process the full constant declaration
+      Rewrite
+        (Bound, Make_Real_Literal (Sloc (Bound), Ureal_0));
+      Analyze (Bound);
+      Resolve (Bound, Standard_Float);
+   end Check_Real_Bound;
 
-      else
-         --  RM 7.4 (6): If the subtype defined by the subtype_indication in
-         --  the deferred declaration is constrained, then the subtype defined
-         --  by the subtype_indication in the full declaration shall match it
-         --  statically.
+   ------------------------------
+   -- Complete_Private_Subtype --
+   ------------------------------
 
-         Check_Possible_Deferred_Completion
-           (Prev_Id      => Prev,
-            Prev_Obj_Def => Object_Definition (Parent (Prev)),
-            Curr_Obj_Def => Obj_Def);
+   procedure Complete_Private_Subtype
+     (Priv        : Entity_Id;
+      Full        : Entity_Id;
+      Full_Base   : Entity_Id;
+      Related_Nod : Node_Id)
+   is
+      Save_Next_Entity : Entity_Id;
+      Save_Homonym     : Entity_Id;
 
-         Set_Full_View (Prev, Id);
-         Set_Is_Public (Id, Is_Public (Prev));
-         Set_Is_Internal (Id);
-         Append_Entity (Id, Current_Scope);
+   begin
+      --  Set semantic attributes for (implicit) private subtype completion.
+      --  If the full type has no discriminants, then it is a copy of the
+      --  full view of the base. Otherwise, it is a subtype of the base with
+      --  a possible discriminant constraint. Save and restore the original
+      --  Next_Entity field of full to ensure that the calls to Copy_Node do
+      --  not corrupt the entity chain.
+
+      --  Note that the type of the full view is the same entity as the type
+      --  of the partial view. In this fashion, the subtype has access to the
+      --  correct view of the parent.
 
-         --  Check ALIASED present if present before (RM 7.4(7))
+      Save_Next_Entity := Next_Entity (Full);
+      Save_Homonym     := Homonym (Priv);
 
-         if Is_Aliased (Prev)
-           and then not Aliased_Present (N)
-         then
-            Error_Msg_Sloc := Sloc (Prev);
-            Error_Msg_N ("ALIASED required (see declaration#)", N);
-         end if;
+      case Ekind (Full_Base) is
+         when E_Record_Type    |
+              E_Record_Subtype |
+              Class_Wide_Kind  |
+              Private_Kind     |
+              Task_Kind        |
+              Protected_Kind   =>
+            Copy_Node (Priv, Full);
 
-         --  Check that placement is in private part and that the incomplete
-         --  declaration appeared in the visible part.
+            Set_Has_Discriminants
+                             (Full, Has_Discriminants (Full_Base));
+            Set_Has_Unknown_Discriminants
+                             (Full, Has_Unknown_Discriminants (Full_Base));
+            Set_First_Entity (Full, First_Entity (Full_Base));
+            Set_Last_Entity  (Full, Last_Entity (Full_Base));
 
-         if Ekind (Current_Scope) = E_Package
-           and then not In_Private_Part (Current_Scope)
-         then
-            Error_Msg_Sloc := Sloc (Prev);
-            Error_Msg_N
-              ("full constant for declaration#"
-               & " must be in private part", N);
+            --  If the underlying base type is constrained, we know that the
+            --  full view of the subtype is constrained as well (the converse
+            --  is not necessarily true).
 
-         elsif Ekind (Current_Scope) = E_Package
-           and then
-             List_Containing (Parent (Prev)) /=
-               Visible_Declarations (Package_Specification (Current_Scope))
-         then
-            Error_Msg_N
-              ("deferred constant must be declared in visible part",
-                 Parent (Prev));
-         end if;
+            if Is_Constrained (Full_Base) then
+               Set_Is_Constrained (Full);
+            end if;
 
-         if Is_Access_Type (T)
-           and then Nkind (Expression (N)) = N_Allocator
-         then
-            Check_Recursive_Declaration (Designated_Type (T));
-         end if;
+         when others =>
+            Copy_Node (Full_Base, Full);
 
-         --  A deferred constant is a visible entity. If type has invariants,
-         --  verify that the initial value satisfies them.
+            Set_Chars         (Full, Chars (Priv));
+            Conditional_Delay (Full, Priv);
+            Set_Sloc          (Full, Sloc (Priv));
+      end case;
 
-         if Has_Invariants (T) and then Present (Invariant_Procedure (T)) then
-            Insert_After (N,
-              Make_Invariant_Call (New_Occurrence_Of (Prev, Sloc (N))));
-         end if;
-      end if;
-   end Constant_Redeclaration;
+      Set_Next_Entity               (Full, Save_Next_Entity);
+      Set_Homonym                   (Full, Save_Homonym);
+      Set_Associated_Node_For_Itype (Full, Related_Nod);
 
-   ----------------------
-   -- Constrain_Access --
-   ----------------------
+      --  Set common attributes for all subtypes: kind, convention, etc.
 
-   procedure Constrain_Access
-     (Def_Id      : in out Entity_Id;
-      S           : Node_Id;
-      Related_Nod : Node_Id)
-   is
-      T             : constant Entity_Id := Entity (Subtype_Mark (S));
-      Desig_Type    : constant Entity_Id := Designated_Type (T);
-      Desig_Subtype : Entity_Id := Create_Itype (E_Void, Related_Nod);
-      Constraint_OK : Boolean := True;
+      Set_Ekind (Full, Subtype_Kind (Ekind (Full_Base)));
+      Set_Convention (Full, Convention (Full_Base));
 
-   begin
-      if Is_Array_Type (Desig_Type) then
-         Constrain_Array (Desig_Subtype, S, Related_Nod, Def_Id, 'P');
+      --  The Etype of the full view is inconsistent. Gigi needs to see the
+      --  structural full view, which is what the current scheme gives: the
+      --  Etype of the full view is the etype of the full base. However, if the
+      --  full base is a derived type, the full view then looks like a subtype
+      --  of the parent, not a subtype of the full base. If instead we write:
 
-      elsif (Is_Record_Type (Desig_Type)
-              or else Is_Incomplete_Or_Private_Type (Desig_Type))
-        and then not Is_Constrained (Desig_Type)
-      then
-         --  ??? The following code is a temporary bypass to ignore a
-         --  discriminant constraint on access type if it is constraining
-         --  the current record. Avoid creating the implicit subtype of the
-         --  record we are currently compiling since right now, we cannot
-         --  handle these. For now, just return the access type itself.
+      --       Set_Etype (Full, Full_Base);
 
-         if Desig_Type = Current_Scope
-           and then No (Def_Id)
-         then
-            Set_Ekind (Desig_Subtype, E_Record_Subtype);
-            Def_Id := Entity (Subtype_Mark (S));
+      --  then we get inconsistencies in the front-end (confusion between
+      --  views). Several outstanding bugs are related to this ???
 
-            --  This call added to ensure that the constraint is analyzed
-            --  (needed for a B test). Note that we still return early from
-            --  this procedure to avoid recursive processing. ???
-
-            Constrain_Discriminated_Type
-              (Desig_Subtype, S, Related_Nod, For_Access => True);
-            return;
-         end if;
-
-         --  Enforce rule that the constraint is illegal if there is an
-         --  unconstrained view of the designated type. This means that the
-         --  partial view (either a private type declaration or a derivation
-         --  from a private type) has no discriminants. (Defect Report
-         --  8652/0008, Technical Corrigendum 1, checked by ACATS B371001).
-
-         --  Rule updated for Ada 2005: The private type is said to have
-         --  a constrained partial view, given that objects of the type
-         --  can be declared. Furthermore, the rule applies to all access
-         --  types, unlike the rule concerning default discriminants (see
-         --  RM 3.7.1(7/3))
+      Set_Is_First_Subtype (Full, False);
+      Set_Scope            (Full, Scope (Priv));
+      Set_Size_Info        (Full, Full_Base);
+      Set_RM_Size          (Full, RM_Size (Full_Base));
+      Set_Is_Itype         (Full);
 
-         if (Ekind (T) = E_General_Access_Type
-              or else Ada_Version >= Ada_2005)
-           and then Has_Private_Declaration (Desig_Type)
-           and then In_Open_Scopes (Scope (Desig_Type))
-           and then Has_Discriminants (Desig_Type)
-         then
-            declare
-               Pack  : constant Node_Id :=
-                         Unit_Declaration_Node (Scope (Desig_Type));
-               Decls : List_Id;
-               Decl  : Node_Id;
+      --  A subtype of a private-type-without-discriminants, whose full-view
+      --  has discriminants with default expressions, is not constrained.
 
-            begin
-               if Nkind (Pack) = N_Package_Declaration then
-                  Decls := Visible_Declarations (Specification (Pack));
-                  Decl := First (Decls);
-                  while Present (Decl) loop
-                     if (Nkind (Decl) = N_Private_Type_Declaration
-                          and then
-                            Chars (Defining_Identifier (Decl)) =
-                                                     Chars (Desig_Type))
+      if not Has_Discriminants (Priv) then
+         Set_Is_Constrained (Full, Is_Constrained (Full_Base));
 
-                       or else
-                        (Nkind (Decl) = N_Full_Type_Declaration
-                          and then
-                            Chars (Defining_Identifier (Decl)) =
-                                                     Chars (Desig_Type)
-                          and then Is_Derived_Type (Desig_Type)
-                          and then
-                            Has_Private_Declaration (Etype (Desig_Type)))
-                     then
-                        if No (Discriminant_Specifications (Decl)) then
-                           Error_Msg_N
-                            ("cannot constrain access type if designated " &
-                               "type has constrained partial view", S);
-                        end if;
+         if Has_Discriminants (Full_Base) then
+            Set_Discriminant_Constraint
+              (Full, Discriminant_Constraint (Full_Base));
 
-                        exit;
-                     end if;
+            --  The partial view may have been indefinite, the full view
+            --  might not be.
 
-                     Next (Decl);
-                  end loop;
-               end if;
-            end;
+            Set_Has_Unknown_Discriminants
+              (Full, Has_Unknown_Discriminants (Full_Base));
          end if;
+      end if;
 
-         Constrain_Discriminated_Type (Desig_Subtype, S, Related_Nod,
-           For_Access => True);
+      Set_First_Rep_Item     (Full, First_Rep_Item (Full_Base));
+      Set_Depends_On_Private (Full, Has_Private_Component (Full));
 
-      elsif (Is_Task_Type (Desig_Type)
-              or else Is_Protected_Type (Desig_Type))
-        and then not Is_Constrained (Desig_Type)
-      then
-         Constrain_Concurrent (Desig_Subtype, S, Related_Nod, Desig_Type, ' ');
+      --  Freeze the private subtype entity if its parent is delayed, and not
+      --  already frozen. We skip this processing if the type is an anonymous
+      --  subtype of a record component, or is the corresponding record of a
+      --  protected type, since these are processed when the enclosing type
+      --  is frozen.
 
-      else
-         Error_Msg_N ("invalid constraint on access type", S);
-         Desig_Subtype := Desig_Type; -- Ignore invalid constraint.
-         Constraint_OK := False;
+      if not Is_Type (Scope (Full)) then
+         Set_Has_Delayed_Freeze (Full,
+           Has_Delayed_Freeze (Full_Base)
+             and then (not Is_Frozen (Full_Base)));
       end if;
 
-      if No (Def_Id) then
-         Def_Id := Create_Itype (E_Access_Subtype, Related_Nod);
-      else
-         Set_Ekind (Def_Id, E_Access_Subtype);
-      end if;
+      Set_Freeze_Node (Full, Empty);
+      Set_Is_Frozen (Full, False);
+      Set_Full_View (Priv, Full);
 
-      if Constraint_OK then
-         Set_Etype (Def_Id, Base_Type (T));
+      if Has_Discriminants (Full) then
+         Set_Stored_Constraint_From_Discriminant_Constraint (Full);
+         Set_Stored_Constraint (Priv, Stored_Constraint (Full));
 
-         if Is_Private_Type (Desig_Type) then
-            Prepare_Private_Subtype_Completion (Desig_Subtype, Related_Nod);
+         if Has_Unknown_Discriminants (Full) then
+            Set_Discriminant_Constraint (Full, No_Elist);
          end if;
-      else
-         Set_Etype (Def_Id, Any_Type);
       end if;
 
-      Set_Size_Info                (Def_Id, T);
-      Set_Is_Constrained           (Def_Id, Constraint_OK);
-      Set_Directly_Designated_Type (Def_Id, Desig_Subtype);
-      Set_Depends_On_Private       (Def_Id, Has_Private_Component (Def_Id));
-      Set_Is_Access_Constant       (Def_Id, Is_Access_Constant (T));
-
-      Conditional_Delay (Def_Id, T);
+      if Ekind (Full_Base) = E_Record_Type
+        and then Has_Discriminants (Full_Base)
+        and then Has_Discriminants (Priv) -- might not, if errors
+        and then not Has_Unknown_Discriminants (Priv)
+        and then not Is_Empty_Elmt_List (Discriminant_Constraint (Priv))
+      then
+         Create_Constrained_Components
+           (Full, Related_Nod, Full_Base, Discriminant_Constraint (Priv));
 
-      --  AI-363 : Subtypes of general access types whose designated types have
-      --  default discriminants are disallowed. In instances, the rule has to
-      --  be checked against the actual, of which T is the subtype. In a
-      --  generic body, the rule is checked assuming that the actual type has
-      --  defaulted discriminants.
+      --  If the full base is itself derived from private, build a congruent
+      --  subtype of its underlying type, for use by the back end. For a
+      --  constrained record component, the declaration cannot be placed on
+      --  the component list, but it must nevertheless be built an analyzed, to
+      --  supply enough information for Gigi to compute the size of component.
 
-      if Ada_Version >= Ada_2005 or else Warn_On_Ada_2005_Compatibility then
-         if Ekind (Base_Type (T)) = E_General_Access_Type
-           and then Has_Defaulted_Discriminants (Desig_Type)
+      elsif Ekind (Full_Base) in Private_Kind
+        and then Is_Derived_Type (Full_Base)
+        and then Has_Discriminants (Full_Base)
+        and then (Ekind (Current_Scope) /= E_Record_Subtype)
+      then
+         if not Is_Itype (Priv)
+           and then
+             Nkind (Subtype_Indication (Parent (Priv))) = N_Subtype_Indication
          then
-            if Ada_Version < Ada_2005 then
-               Error_Msg_N
-                 ("access subtype of general access type would not " &
-                  "be allowed in Ada 2005?y?", S);
-            else
-               Error_Msg_N
-                 ("access subtype of general access type not allowed", S);
-            end if;
+            Build_Underlying_Full_View
+              (Parent (Priv), Full, Etype (Full_Base));
 
-            Error_Msg_N ("\discriminants have defaults", S);
+         elsif Nkind (Related_Nod) = N_Component_Declaration then
+            Build_Underlying_Full_View (Related_Nod, Full, Etype (Full_Base));
+         end if;
 
-         elsif Is_Access_Type (T)
-           and then Is_Generic_Type (Desig_Type)
-           and then Has_Discriminants (Desig_Type)
-           and then In_Package_Body (Current_Scope)
-         then
-            if Ada_Version < Ada_2005 then
-               Error_Msg_N
-                 ("access subtype would not be allowed in generic body " &
-                  "in Ada 2005?y?", S);
-            else
-               Error_Msg_N
-                 ("access subtype not allowed in generic body", S);
-            end if;
+      elsif Is_Record_Type (Full_Base) then
 
-            Error_Msg_N
-              ("\designated type is a discriminated formal", S);
-         end if;
+         --  Show Full is simply a renaming of Full_Base
+
+         Set_Cloned_Subtype (Full, Full_Base);
       end if;
-   end Constrain_Access;
 
-   ---------------------
-   -- Constrain_Array --
-   ---------------------
+      --  It is unsafe to share the bounds of a scalar type, because the Itype
+      --  is elaborated on demand, and if a bound is non-static then different
+      --  orders of elaboration in different units will lead to different
+      --  external symbols.
 
-   procedure Constrain_Array
-     (Def_Id      : in out Entity_Id;
-      SI          : Node_Id;
-      Related_Nod : Node_Id;
-      Related_Id  : Entity_Id;
-      Suffix      : Character)
-   is
-      C                     : constant Node_Id := Constraint (SI);
-      Number_Of_Constraints : Nat := 0;
-      Index                 : Node_Id;
-      S, T                  : Entity_Id;
-      Constraint_OK         : Boolean := True;
+      if Is_Scalar_Type (Full_Base) then
+         Set_Scalar_Range (Full,
+           Make_Range (Sloc (Related_Nod),
+             Low_Bound  =>
+               Duplicate_Subexpr_No_Checks (Type_Low_Bound  (Full_Base)),
+             High_Bound =>
+               Duplicate_Subexpr_No_Checks (Type_High_Bound (Full_Base))));
 
-   begin
-      T := Entity (Subtype_Mark (SI));
+         --  This completion inherits the bounds of the full parent, but if
+         --  the parent is an unconstrained floating point type, so is the
+         --  completion.
 
-      if Is_Access_Type (T) then
-         T := Designated_Type (T);
+         if Is_Floating_Point_Type (Full_Base) then
+            Set_Includes_Infinities
+             (Scalar_Range (Full), Has_Infinities (Full_Base));
+         end if;
       end if;
 
-      --  If an index constraint follows a subtype mark in a subtype indication
-      --  then the type or subtype denoted by the subtype mark must not already
-      --  impose an index constraint. The subtype mark must denote either an
-      --  unconstrained array type or an access type whose designated type
-      --  is such an array type... (RM 3.6.1)
-
-      if Is_Constrained (T) then
-         Error_Msg_N ("array type is already constrained", Subtype_Mark (SI));
-         Constraint_OK := False;
-
-      else
-         S := First (Constraints (C));
-         while Present (S) loop
-            Number_Of_Constraints := Number_Of_Constraints + 1;
-            Next (S);
-         end loop;
+      --  ??? It seems that a lot of fields are missing that should be copied
+      --  from Full_Base to Full. Here are some that are introduced in a
+      --  non-disruptive way but a cleanup is necessary.
 
-         --  In either case, the index constraint must provide a discrete
-         --  range for each index of the array type and the type of each
-         --  discrete range must be the same as that of the corresponding
-         --  index. (RM 3.6.1)
+      if Is_Tagged_Type (Full_Base) then
+         Set_Is_Tagged_Type (Full);
+         Set_Direct_Primitive_Operations
+           (Full, Direct_Primitive_Operations (Full_Base));
+         Set_No_Tagged_Streams_Pragma
+           (Full, No_Tagged_Streams_Pragma (Full_Base));
 
-         if Number_Of_Constraints /= Number_Dimensions (T) then
-            Error_Msg_NE ("incorrect number of index constraints for }", C, T);
-            Constraint_OK := False;
+         --  Inherit class_wide type of full_base in case the partial view was
+         --  not tagged. Otherwise it has already been created when the private
+         --  subtype was analyzed.
 
-         else
-            S := First (Constraints (C));
-            Index := First_Index (T);
-            Analyze (Index);
+         if No (Class_Wide_Type (Full)) then
+            Set_Class_Wide_Type (Full, Class_Wide_Type (Full_Base));
+         end if;
 
-            --  Apply constraints to each index type
+      --  If this is a subtype of a protected or task type, constrain its
+      --  corresponding record, unless this is a subtype without constraints,
+      --  i.e. a simple renaming as with an actual subtype in an instance.
 
-            for J in 1 .. Number_Of_Constraints loop
-               Constrain_Index (Index, S, Related_Nod, Related_Id, Suffix, J);
-               Next (Index);
-               Next (S);
-            end loop;
+      elsif Is_Concurrent_Type (Full_Base) then
+         if Has_Discriminants (Full)
+           and then Present (Corresponding_Record_Type (Full_Base))
+           and then
+             not Is_Empty_Elmt_List (Discriminant_Constraint (Full))
+         then
+            Set_Corresponding_Record_Type (Full,
+              Constrain_Corresponding_Record
+                (Full, Corresponding_Record_Type (Full_Base), Related_Nod));
 
+         else
+            Set_Corresponding_Record_Type (Full,
+              Corresponding_Record_Type (Full_Base));
          end if;
       end if;
 
-      if No (Def_Id) then
-         Def_Id :=
-           Create_Itype (E_Array_Subtype, Related_Nod, Related_Id, Suffix);
-         Set_Parent (Def_Id, Related_Nod);
+      --  Link rep item chain, and also setting of Has_Predicates from private
+      --  subtype to full subtype, since we will need these on the full subtype
+      --  to create the predicate function. Note that the full subtype may
+      --  already have rep items, inherited from the full view of the base
+      --  type, so we must be sure not to overwrite these entries.
 
-      else
-         Set_Ekind (Def_Id, E_Array_Subtype);
-      end if;
+      declare
+         Append    : Boolean;
+         Item      : Node_Id;
+         Next_Item : Node_Id;
 
-      Set_Size_Info      (Def_Id,                (T));
-      Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
-      Set_Etype          (Def_Id, Base_Type      (T));
+      begin
+         Item := First_Rep_Item (Full);
 
-      if Constraint_OK then
-         Set_First_Index (Def_Id, First (Constraints (C)));
-      else
-         Set_First_Index (Def_Id, First_Index (T));
-      end if;
+         --  If no existing rep items on full type, we can just link directly
+         --  to the list of items on the private type, if any exist.. Same if
+         --  the rep items are only those inherited from the base
 
-      Set_Is_Constrained     (Def_Id, True);
-      Set_Is_Aliased         (Def_Id, Is_Aliased (T));
-      Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
+         if (No (Item)
+              or else Nkind (Item) /= N_Aspect_Specification
+              or else Entity (Item) = Full_Base)
+             and then Present (First_Rep_Item (Priv))
+         then
+            Set_First_Rep_Item (Full, First_Rep_Item (Priv));
 
-      Set_Is_Private_Composite (Def_Id, Is_Private_Composite (T));
-      Set_Is_Limited_Composite (Def_Id, Is_Limited_Composite (T));
+         --  Otherwise, search to the end of items currently linked to the full
+         --  subtype and append the private items to the end. However, if Priv
+         --  and Full already have the same list of rep items, then the append
+         --  is not done, as that would create a circularity.
 
-      --  A subtype does not inherit the Packed_Array_Impl_Type of is parent.
-      --  We need to initialize the attribute because if Def_Id is previously
-      --  analyzed through a limited_with clause, it will have the attributes
-      --  of an incomplete type, one of which is an Elist that overlaps the
-      --  Packed_Array_Impl_Type field.
+         elsif Item /= First_Rep_Item (Priv) then
+            Append := True;
+            loop
+               Next_Item := Next_Rep_Item (Item);
+               exit when No (Next_Item);
+               Item := Next_Item;
 
-      Set_Packed_Array_Impl_Type (Def_Id, Empty);
+               --  If the private view has aspect specifications, the full view
+               --  inherits them. Since these aspects may already have been
+               --  attached to the full view during derivation, do not append
+               --  them if already present.
 
-      --  Build a freeze node if parent still needs one. Also make sure that
-      --  the Depends_On_Private status is set because the subtype will need
-      --  reprocessing at the time the base type does, and also we must set a
-      --  conditional delay.
+               if Item = First_Rep_Item (Priv) then
+                  Append := False;
+                  exit;
+               end if;
+            end loop;
 
-      Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
-      Conditional_Delay (Def_Id, T);
-   end Constrain_Array;
+            --  And link the private type items at the end of the chain
 
-   ------------------------------
-   -- Constrain_Component_Type --
-   ------------------------------
+            if Append then
+               Set_Next_Rep_Item (Item, First_Rep_Item (Priv));
+            end if;
+         end if;
+      end;
 
-   function Constrain_Component_Type
-     (Comp            : Entity_Id;
-      Constrained_Typ : Entity_Id;
-      Related_Node    : Node_Id;
-      Typ             : Entity_Id;
-      Constraints     : Elist_Id) return Entity_Id
-   is
-      Loc         : constant Source_Ptr := Sloc (Constrained_Typ);
-      Compon_Type : constant Entity_Id := Etype (Comp);
+      --  Make sure Has_Predicates is set on full type if it is set on the
+      --  private type. Note that it may already be set on the full type and
+      --  if so, we don't want to unset it. Similarly, propagate information
+      --  about delayed aspects, because the corresponding pragmas must be
+      --  analyzed when one of the views is frozen. This last step is needed
+      --  in particular when the full type is a scalar type for which an
+      --  anonymous base type is constructed.
 
-      function Build_Constrained_Array_Type
-        (Old_Type : Entity_Id) return Entity_Id;
-      --  If Old_Type is an array type, one of whose indexes is constrained
-      --  by a discriminant, build an Itype whose constraint replaces the
-      --  discriminant with its value in the constraint.
+      if Has_Predicates (Priv) then
+         Set_Has_Predicates (Full);
+      end if;
 
-      function Build_Constrained_Discriminated_Type
-        (Old_Type : Entity_Id) return Entity_Id;
-      --  Ditto for record components
+      if Has_Delayed_Aspects (Priv) then
+         Set_Has_Delayed_Aspects (Full);
+      end if;
+   end Complete_Private_Subtype;
 
-      function Build_Constrained_Access_Type
-        (Old_Type : Entity_Id) return Entity_Id;
-      --  Ditto for access types. Makes use of previous two functions, to
-      --  constrain designated type.
+   ----------------------------
+   -- Constant_Redeclaration --
+   ----------------------------
 
-      function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id;
-      --  T is an array or discriminated type, C is a list of constraints
-      --  that apply to T. This routine builds the constrained subtype.
+   procedure Constant_Redeclaration
+     (Id : Entity_Id;
+      N  : Node_Id;
+      T  : out Entity_Id)
+   is
+      Prev    : constant Entity_Id := Current_Entity_In_Scope (Id);
+      Obj_Def : constant Node_Id := Object_Definition (N);
+      New_T   : Entity_Id;
 
-      function Is_Discriminant (Expr : Node_Id) return Boolean;
-      --  Returns True if Expr is a discriminant
+      procedure Check_Possible_Deferred_Completion
+        (Prev_Id      : Entity_Id;
+         Prev_Obj_Def : Node_Id;
+         Curr_Obj_Def : Node_Id);
+      --  Determine whether the two object definitions describe the partial
+      --  and the full view of a constrained deferred constant. Generate
+      --  a subtype for the full view and verify that it statically matches
+      --  the subtype of the partial view.
 
-      function Get_Discr_Value (Discrim : Entity_Id) return Node_Id;
-      --  Find the value of discriminant Discrim in Constraint
+      procedure Check_Recursive_Declaration (Typ : Entity_Id);
+      --  If deferred constant is an access type initialized with an allocator,
+      --  check whether there is an illegal recursion in the definition,
+      --  through a default value of some record subcomponent. This is normally
+      --  detected when generating init procs, but requires this additional
+      --  mechanism when expansion is disabled.
 
-      -----------------------------------
-      -- Build_Constrained_Access_Type --
-      -----------------------------------
+      ----------------------------------------
+      -- Check_Possible_Deferred_Completion --
+      ----------------------------------------
 
-      function Build_Constrained_Access_Type
-        (Old_Type : Entity_Id) return Entity_Id
+      procedure Check_Possible_Deferred_Completion
+        (Prev_Id      : Entity_Id;
+         Prev_Obj_Def : Node_Id;
+         Curr_Obj_Def : Node_Id)
       is
-         Desig_Type    : constant Entity_Id := Designated_Type (Old_Type);
-         Itype         : Entity_Id;
-         Desig_Subtype : Entity_Id;
-         Scop          : Entity_Id;
-
       begin
-         --  if the original access type was not embedded in the enclosing
-         --  type definition, there is no need to produce a new access
-         --  subtype. In fact every access type with an explicit constraint
-         --  generates an itype whose scope is the enclosing record.
-
-         if not Is_Type (Scope (Old_Type)) then
-            return Old_Type;
+         if Nkind (Prev_Obj_Def) = N_Subtype_Indication
+           and then Present (Constraint (Prev_Obj_Def))
+           and then Nkind (Curr_Obj_Def) = N_Subtype_Indication
+           and then Present (Constraint (Curr_Obj_Def))
+         then
+            declare
+               Loc    : constant Source_Ptr := Sloc (N);
+               Def_Id : constant Entity_Id  := Make_Temporary (Loc, 'S');
+               Decl   : constant Node_Id    :=
+                          Make_Subtype_Declaration (Loc,
+                            Defining_Identifier => Def_Id,
+                            Subtype_Indication  =>
+                              Relocate_Node (Curr_Obj_Def));
 
-         elsif Is_Array_Type (Desig_Type) then
-            Desig_Subtype := Build_Constrained_Array_Type (Desig_Type);
+            begin
+               Insert_Before_And_Analyze (N, Decl);
+               Set_Etype (Id, Def_Id);
 
-         elsif Has_Discriminants (Desig_Type) then
+               if not Subtypes_Statically_Match (Etype (Prev_Id), Def_Id) then
+                  Error_Msg_Sloc := Sloc (Prev_Id);
+                  Error_Msg_N ("subtype does not statically match deferred "
+                               & "declaration #", N);
+               end if;
+            end;
+         end if;
+      end Check_Possible_Deferred_Completion;
 
-            --  This may be an access type to an enclosing record type for
-            --  which we are constructing the constrained components. Return
-            --  the enclosing record subtype. This is not always correct,
-            --  but avoids infinite recursion. ???
+      ---------------------------------
+      -- Check_Recursive_Declaration --
+      ---------------------------------
 
-            Desig_Subtype := Any_Type;
+      procedure Check_Recursive_Declaration (Typ : Entity_Id) is
+         Comp : Entity_Id;
 
-            for J in reverse 0 .. Scope_Stack.Last loop
-               Scop := Scope_Stack.Table (J).Entity;
+      begin
+         if Is_Record_Type (Typ) then
+            Comp := First_Component (Typ);
+            while Present (Comp) loop
+               if Comes_From_Source (Comp) then
+                  if Present (Expression (Parent (Comp)))
+                    and then Is_Entity_Name (Expression (Parent (Comp)))
+                    and then Entity (Expression (Parent (Comp))) = Prev
+                  then
+                     Error_Msg_Sloc := Sloc (Parent (Comp));
+                     Error_Msg_NE
+                       ("illegal circularity with declaration for & #",
+                         N, Comp);
+                     return;
 
-               if Is_Type (Scop)
-                 and then Base_Type (Scop) = Base_Type (Desig_Type)
-               then
-                  Desig_Subtype := Scop;
+                  elsif Is_Record_Type (Etype (Comp)) then
+                     Check_Recursive_Declaration (Etype (Comp));
+                  end if;
                end if;
 
-               exit when not Is_Type (Scop);
+               Next_Component (Comp);
             end loop;
-
-            if Desig_Subtype = Any_Type then
-               Desig_Subtype :=
-                 Build_Constrained_Discriminated_Type (Desig_Type);
-            end if;
-
-         else
-            return Old_Type;
          end if;
+      end Check_Recursive_Declaration;
 
-         if Desig_Subtype /= Desig_Type then
+   --  Start of processing for Constant_Redeclaration
 
-            --  The Related_Node better be here or else we won't be able
-            --  to attach new itypes to a node in the tree.
+   begin
+      if Nkind (Parent (Prev)) = N_Object_Declaration then
+         if Nkind (Object_Definition
+                     (Parent (Prev))) = N_Subtype_Indication
+         then
+            --  Find type of new declaration. The constraints of the two
+            --  views must match statically, but there is no point in
+            --  creating an itype for the full view.
 
-            pragma Assert (Present (Related_Node));
-
-            Itype := Create_Itype (E_Access_Subtype, Related_Node);
-
-            Set_Etype                    (Itype, Base_Type      (Old_Type));
-            Set_Size_Info                (Itype,                (Old_Type));
-            Set_Directly_Designated_Type (Itype, Desig_Subtype);
-            Set_Depends_On_Private       (Itype, Has_Private_Component
-                                                                (Old_Type));
-            Set_Is_Access_Constant       (Itype, Is_Access_Constant
-                                                                (Old_Type));
-
-            --  The new itype needs freezing when it depends on a not frozen
-            --  type and the enclosing subtype needs freezing.
+            if Nkind (Obj_Def) = N_Subtype_Indication then
+               Find_Type (Subtype_Mark (Obj_Def));
+               New_T := Entity (Subtype_Mark (Obj_Def));
 
-            if Has_Delayed_Freeze (Constrained_Typ)
-              and then not Is_Frozen (Constrained_Typ)
-            then
-               Conditional_Delay (Itype, Base_Type (Old_Type));
+            else
+               Find_Type (Obj_Def);
+               New_T := Entity (Obj_Def);
             end if;
 
-            return Itype;
+            T := Etype (Prev);
 
          else
-            return Old_Type;
+            --  The full view may impose a constraint, even if the partial
+            --  view does not, so construct the subtype.
+
+            New_T := Find_Type_Of_Object (Obj_Def, N);
+            T     := New_T;
          end if;
-      end Build_Constrained_Access_Type;
 
-      ----------------------------------
-      -- Build_Constrained_Array_Type --
-      ----------------------------------
+      else
+         --  Current declaration is illegal, diagnosed below in Enter_Name
 
-      function Build_Constrained_Array_Type
-        (Old_Type : Entity_Id) return Entity_Id
-      is
-         Lo_Expr     : Node_Id;
-         Hi_Expr     : Node_Id;
-         Old_Index   : Node_Id;
-         Range_Node  : Node_Id;
-         Constr_List : List_Id;
+         T := Empty;
+         New_T := Any_Type;
+      end if;
 
-         Need_To_Create_Itype : Boolean := False;
+      --  If previous full declaration or a renaming declaration exists, or if
+      --  a homograph is present, let Enter_Name handle it, either with an
+      --  error or with the removal of an overridden implicit subprogram.
+      --  The previous one is a full declaration if it has an expression
+      --  (which in the case of an aggregate is indicated by the Init flag).
 
-      begin
-         Old_Index := First_Index (Old_Type);
-         while Present (Old_Index) loop
-            Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
+      if Ekind (Prev) /= E_Constant
+        or else Nkind (Parent (Prev)) = N_Object_Renaming_Declaration
+        or else Present (Expression (Parent (Prev)))
+        or else Has_Init_Expression (Parent (Prev))
+        or else Present (Full_View (Prev))
+      then
+         Enter_Name (Id);
 
-            if Is_Discriminant (Lo_Expr)
-              or else Is_Discriminant (Hi_Expr)
-            then
-               Need_To_Create_Itype := True;
-            end if;
+      --  Verify that types of both declarations match, or else that both types
+      --  are anonymous access types whose designated subtypes statically match
+      --  (as allowed in Ada 2005 by AI-385).
 
-            Next_Index (Old_Index);
-         end loop;
+      elsif Base_Type (Etype (Prev)) /= Base_Type (New_T)
+        and then
+          (Ekind (Etype (Prev)) /= E_Anonymous_Access_Type
+             or else Ekind (Etype (New_T)) /= E_Anonymous_Access_Type
+             or else Is_Access_Constant (Etype (New_T)) /=
+                     Is_Access_Constant (Etype (Prev))
+             or else Can_Never_Be_Null (Etype (New_T)) /=
+                     Can_Never_Be_Null (Etype (Prev))
+             or else Null_Exclusion_Present (Parent (Prev)) /=
+                     Null_Exclusion_Present (Parent (Id))
+             or else not Subtypes_Statically_Match
+                           (Designated_Type (Etype (Prev)),
+                            Designated_Type (Etype (New_T))))
+      then
+         Error_Msg_Sloc := Sloc (Prev);
+         Error_Msg_N ("type does not match declaration#", N);
+         Set_Full_View (Prev, Id);
+         Set_Etype (Id, Any_Type);
 
-         if Need_To_Create_Itype then
-            Constr_List := New_List;
+         --  A deferred constant whose type is an anonymous array is always
+         --  illegal (unless imported). A detailed error message might be
+         --  helpful for Ada beginners.
 
-            Old_Index := First_Index (Old_Type);
-            while Present (Old_Index) loop
-               Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
+         if Nkind (Object_Definition (Parent (Prev)))
+            = N_Constrained_Array_Definition
+           and then Nkind (Object_Definition (N))
+              = N_Constrained_Array_Definition
+         then
+            Error_Msg_N ("\each anonymous array is a distinct type", N);
+            Error_Msg_N ("a deferred constant must have a named type",
+              Object_Definition (Parent (Prev)));
+         end if;
 
-               if Is_Discriminant (Lo_Expr) then
-                  Lo_Expr := Get_Discr_Value (Lo_Expr);
-               end if;
+      elsif
+        Null_Exclusion_Present (Parent (Prev))
+          and then not Null_Exclusion_Present (N)
+      then
+         Error_Msg_Sloc := Sloc (Prev);
+         Error_Msg_N ("null-exclusion does not match declaration#", N);
+         Set_Full_View (Prev, Id);
+         Set_Etype (Id, Any_Type);
 
-               if Is_Discriminant (Hi_Expr) then
-                  Hi_Expr := Get_Discr_Value (Hi_Expr);
-               end if;
+      --  If so, process the full constant declaration
 
-               Range_Node :=
-                 Make_Range
-                   (Loc, New_Copy_Tree (Lo_Expr), New_Copy_Tree (Hi_Expr));
+      else
+         --  RM 7.4 (6): If the subtype defined by the subtype_indication in
+         --  the deferred declaration is constrained, then the subtype defined
+         --  by the subtype_indication in the full declaration shall match it
+         --  statically.
 
-               Append (Range_Node, To => Constr_List);
+         Check_Possible_Deferred_Completion
+           (Prev_Id      => Prev,
+            Prev_Obj_Def => Object_Definition (Parent (Prev)),
+            Curr_Obj_Def => Obj_Def);
 
-               Next_Index (Old_Index);
-            end loop;
+         Set_Full_View (Prev, Id);
+         Set_Is_Public (Id, Is_Public (Prev));
+         Set_Is_Internal (Id);
+         Append_Entity (Id, Current_Scope);
 
-            return Build_Subtype (Old_Type, Constr_List);
+         --  Check ALIASED present if present before (RM 7.4(7))
 
-         else
-            return Old_Type;
+         if Is_Aliased (Prev)
+           and then not Aliased_Present (N)
+         then
+            Error_Msg_Sloc := Sloc (Prev);
+            Error_Msg_N ("ALIASED required (see declaration #)", N);
          end if;
-      end Build_Constrained_Array_Type;
 
-      ------------------------------------------
-      -- Build_Constrained_Discriminated_Type --
-      ------------------------------------------
+         --  Check that placement is in private part and that the incomplete
+         --  declaration appeared in the visible part.
 
-      function Build_Constrained_Discriminated_Type
-        (Old_Type : Entity_Id) return Entity_Id
-      is
-         Expr           : Node_Id;
-         Constr_List    : List_Id;
-         Old_Constraint : Elmt_Id;
+         if Ekind (Current_Scope) = E_Package
+           and then not In_Private_Part (Current_Scope)
+         then
+            Error_Msg_Sloc := Sloc (Prev);
+            Error_Msg_N
+              ("full constant for declaration # must be in private part", N);
 
-         Need_To_Create_Itype : Boolean := False;
+         elsif Ekind (Current_Scope) = E_Package
+           and then
+             List_Containing (Parent (Prev)) /=
+               Visible_Declarations (Package_Specification (Current_Scope))
+         then
+            Error_Msg_N
+              ("deferred constant must be declared in visible part",
+                 Parent (Prev));
+         end if;
 
-      begin
-         Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
-         while Present (Old_Constraint) loop
-            Expr := Node (Old_Constraint);
+         if Is_Access_Type (T)
+           and then Nkind (Expression (N)) = N_Allocator
+         then
+            Check_Recursive_Declaration (Designated_Type (T));
+         end if;
 
-            if Is_Discriminant (Expr) then
-               Need_To_Create_Itype := True;
-            end if;
+         --  A deferred constant is a visible entity. If type has invariants,
+         --  verify that the initial value satisfies them.
 
-            Next_Elmt (Old_Constraint);
-         end loop;
+         if Has_Invariants (T) and then Present (Invariant_Procedure (T)) then
+            Insert_After (N,
+              Make_Invariant_Call (New_Occurrence_Of (Prev, Sloc (N))));
+         end if;
+      end if;
+   end Constant_Redeclaration;
 
-         if Need_To_Create_Itype then
-            Constr_List := New_List;
+   ----------------------
+   -- Constrain_Access --
+   ----------------------
 
-            Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
-            while Present (Old_Constraint) loop
-               Expr := Node (Old_Constraint);
+   procedure Constrain_Access
+     (Def_Id      : in out Entity_Id;
+      S           : Node_Id;
+      Related_Nod : Node_Id)
+   is
+      T             : constant Entity_Id := Entity (Subtype_Mark (S));
+      Desig_Type    : constant Entity_Id := Designated_Type (T);
+      Desig_Subtype : Entity_Id := Create_Itype (E_Void, Related_Nod);
+      Constraint_OK : Boolean := True;
 
-               if Is_Discriminant (Expr) then
-                  Expr := Get_Discr_Value (Expr);
-               end if;
+   begin
+      if Is_Array_Type (Desig_Type) then
+         Constrain_Array (Desig_Subtype, S, Related_Nod, Def_Id, 'P');
 
-               Append (New_Copy_Tree (Expr), To => Constr_List);
+      elsif (Is_Record_Type (Desig_Type)
+              or else Is_Incomplete_Or_Private_Type (Desig_Type))
+        and then not Is_Constrained (Desig_Type)
+      then
+         --  ??? The following code is a temporary bypass to ignore a
+         --  discriminant constraint on access type if it is constraining
+         --  the current record. Avoid creating the implicit subtype of the
+         --  record we are currently compiling since right now, we cannot
+         --  handle these. For now, just return the access type itself.
 
-               Next_Elmt (Old_Constraint);
-            end loop;
+         if Desig_Type = Current_Scope
+           and then No (Def_Id)
+         then
+            Set_Ekind (Desig_Subtype, E_Record_Subtype);
+            Def_Id := Entity (Subtype_Mark (S));
 
-            return Build_Subtype (Old_Type, Constr_List);
+            --  This call added to ensure that the constraint is analyzed
+            --  (needed for a B test). Note that we still return early from
+            --  this procedure to avoid recursive processing. ???
 
-         else
-            return Old_Type;
+            Constrain_Discriminated_Type
+              (Desig_Subtype, S, Related_Nod, For_Access => True);
+            return;
          end if;
-      end Build_Constrained_Discriminated_Type;
-
-      -------------------
-      -- Build_Subtype --
-      -------------------
 
-      function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id is
-         Indic       : Node_Id;
-         Subtyp_Decl : Node_Id;
-         Def_Id      : Entity_Id;
-         Btyp        : Entity_Id := Base_Type (T);
+         --  Enforce rule that the constraint is illegal if there is an
+         --  unconstrained view of the designated type. This means that the
+         --  partial view (either a private type declaration or a derivation
+         --  from a private type) has no discriminants. (Defect Report
+         --  8652/0008, Technical Corrigendum 1, checked by ACATS B371001).
 
-      begin
-         --  The Related_Node better be here or else we won't be able to
-         --  attach new itypes to a node in the tree.
+         --  Rule updated for Ada 2005: The private type is said to have
+         --  a constrained partial view, given that objects of the type
+         --  can be declared. Furthermore, the rule applies to all access
+         --  types, unlike the rule concerning default discriminants (see
+         --  RM 3.7.1(7/3))
 
-         pragma Assert (Present (Related_Node));
+         if (Ekind (T) = E_General_Access_Type or else Ada_Version >= Ada_2005)
+           and then Has_Private_Declaration (Desig_Type)
+           and then In_Open_Scopes (Scope (Desig_Type))
+           and then Has_Discriminants (Desig_Type)
+         then
+            declare
+               Pack  : constant Node_Id :=
+                         Unit_Declaration_Node (Scope (Desig_Type));
+               Decls : List_Id;
+               Decl  : Node_Id;
 
-         --  If the view of the component's type is incomplete or private
-         --  with unknown discriminants, then the constraint must be applied
-         --  to the full type.
+            begin
+               if Nkind (Pack) = N_Package_Declaration then
+                  Decls := Visible_Declarations (Specification (Pack));
+                  Decl := First (Decls);
+                  while Present (Decl) loop
+                     if (Nkind (Decl) = N_Private_Type_Declaration
+                          and then Chars (Defining_Identifier (Decl)) =
+                                                           Chars (Desig_Type))
 
-         if Has_Unknown_Discriminants (Btyp)
-           and then Present (Underlying_Type (Btyp))
-         then
-            Btyp := Underlying_Type (Btyp);
-         end if;
+                       or else
+                        (Nkind (Decl) = N_Full_Type_Declaration
+                          and then
+                            Chars (Defining_Identifier (Decl)) =
+                                                     Chars (Desig_Type)
+                          and then Is_Derived_Type (Desig_Type)
+                          and then
+                            Has_Private_Declaration (Etype (Desig_Type)))
+                     then
+                        if No (Discriminant_Specifications (Decl)) then
+                           Error_Msg_N
+                             ("cannot constrain access type if designated "
+                              & "type has constrained partial view", S);
+                        end if;
 
-         Indic :=
-           Make_Subtype_Indication (Loc,
-             Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
-             Constraint   => Make_Index_Or_Discriminant_Constraint (Loc, C));
+                        exit;
+                     end if;
 
-         Def_Id := Create_Itype (Ekind (T), Related_Node);
+                     Next (Decl);
+                  end loop;
+               end if;
+            end;
+         end if;
 
-         Subtyp_Decl :=
-           Make_Subtype_Declaration (Loc,
-             Defining_Identifier => Def_Id,
-             Subtype_Indication  => Indic);
+         Constrain_Discriminated_Type (Desig_Subtype, S, Related_Nod,
+           For_Access => True);
 
-         Set_Parent (Subtyp_Decl, Parent (Related_Node));
+      elsif Is_Concurrent_Type (Desig_Type)
+        and then not Is_Constrained (Desig_Type)
+      then
+         Constrain_Concurrent (Desig_Subtype, S, Related_Nod, Desig_Type, ' ');
 
-         --  Itypes must be analyzed with checks off (see package Itypes)
+      else
+         Error_Msg_N ("invalid constraint on access type", S);
 
-         Analyze (Subtyp_Decl, Suppress => All_Checks);
+         --  We simply ignore an invalid constraint
 
-         return Def_Id;
-      end Build_Subtype;
+         Desig_Subtype := Desig_Type;
+         Constraint_OK := False;
+      end if;
 
-      ---------------------
-      -- Get_Discr_Value --
-      ---------------------
+      if No (Def_Id) then
+         Def_Id := Create_Itype (E_Access_Subtype, Related_Nod);
+      else
+         Set_Ekind (Def_Id, E_Access_Subtype);
+      end if;
 
-      function Get_Discr_Value (Discrim : Entity_Id) return Node_Id is
-         D : Entity_Id;
-         E : Elmt_Id;
+      if Constraint_OK then
+         Set_Etype (Def_Id, Base_Type (T));
 
-      begin
-         --  The discriminant may be declared for the type, in which case we
-         --  find it by iterating over the list of discriminants. If the
-         --  discriminant is inherited from a parent type, it appears as the
-         --  corresponding discriminant of the current type. This will be the
-         --  case when constraining an inherited component whose constraint is
-         --  given by a discriminant of the parent.
+         if Is_Private_Type (Desig_Type) then
+            Prepare_Private_Subtype_Completion (Desig_Subtype, Related_Nod);
+         end if;
+      else
+         Set_Etype (Def_Id, Any_Type);
+      end if;
 
-         D := First_Discriminant (Typ);
-         E := First_Elmt (Constraints);
+      Set_Size_Info                (Def_Id, T);
+      Set_Is_Constrained           (Def_Id, Constraint_OK);
+      Set_Directly_Designated_Type (Def_Id, Desig_Subtype);
+      Set_Depends_On_Private       (Def_Id, Has_Private_Component (Def_Id));
+      Set_Is_Access_Constant       (Def_Id, Is_Access_Constant (T));
 
-         while Present (D) loop
-            if D = Entity (Discrim)
-              or else D = CR_Discriminant (Entity (Discrim))
-              or else Corresponding_Discriminant (D) = Entity (Discrim)
-            then
-               return Node (E);
-            end if;
+      Conditional_Delay (Def_Id, T);
 
-            Next_Discriminant (D);
-            Next_Elmt (E);
-         end loop;
+      --  AI-363 : Subtypes of general access types whose designated types have
+      --  default discriminants are disallowed. In instances, the rule has to
+      --  be checked against the actual, of which T is the subtype. In a
+      --  generic body, the rule is checked assuming that the actual type has
+      --  defaulted discriminants.
 
-         --  The Corresponding_Discriminant mechanism is incomplete, because
-         --  the correspondence between new and old discriminants is not one
-         --  to one: one new discriminant can constrain several old ones. In
-         --  that case, scan sequentially the stored_constraint, the list of
-         --  discriminants of the parents, and the constraints.
+      if Ada_Version >= Ada_2005 or else Warn_On_Ada_2005_Compatibility then
+         if Ekind (Base_Type (T)) = E_General_Access_Type
+           and then Has_Defaulted_Discriminants (Desig_Type)
+         then
+            if Ada_Version < Ada_2005 then
+               Error_Msg_N
+                 ("access subtype of general access type would not " &
+                  "be allowed in Ada 2005?y?", S);
+            else
+               Error_Msg_N
+                 ("access subtype of general access type not allowed", S);
+            end if;
 
-         --  Previous code checked for the present of the Stored_Constraint
-         --  list for the derived type, but did not use it at all. Should it
-         --  be present when the component is a discriminated task type?
+            Error_Msg_N ("\discriminants have defaults", S);
 
-         if Is_Derived_Type (Typ)
-           and then Scope (Entity (Discrim)) = Etype (Typ)
+         elsif Is_Access_Type (T)
+           and then Is_Generic_Type (Desig_Type)
+           and then Has_Discriminants (Desig_Type)
+           and then In_Package_Body (Current_Scope)
          then
-            D := First_Discriminant (Etype (Typ));
-            E := First_Elmt (Constraints);
-            while Present (D) loop
-               if D = Entity (Discrim) then
-                  return Node (E);
-               end if;
+            if Ada_Version < Ada_2005 then
+               Error_Msg_N
+                 ("access subtype would not be allowed in generic body "
+                  & "in Ada 2005?y?", S);
+            else
+               Error_Msg_N
+                 ("access subtype not allowed in generic body", S);
+            end if;
 
-               Next_Discriminant (D);
-               Next_Elmt (E);
-            end loop;
+            Error_Msg_N
+              ("\designated type is a discriminated formal", S);
          end if;
+      end if;
+   end Constrain_Access;
 
-         --  Something is wrong if we did not find the value
-
-         raise Program_Error;
-      end Get_Discr_Value;
+   ---------------------
+   -- Constrain_Array --
+   ---------------------
 
-      ---------------------
-      -- Is_Discriminant --
-      ---------------------
+   procedure Constrain_Array
+     (Def_Id      : in out Entity_Id;
+      SI          : Node_Id;
+      Related_Nod : Node_Id;
+      Related_Id  : Entity_Id;
+      Suffix      : Character)
+   is
+      C                     : constant Node_Id := Constraint (SI);
+      Number_Of_Constraints : Nat := 0;
+      Index                 : Node_Id;
+      S, T                  : Entity_Id;
+      Constraint_OK         : Boolean := True;
 
-      function Is_Discriminant (Expr : Node_Id) return Boolean is
-         Discrim_Scope : Entity_Id;
+   begin
+      T := Entity (Subtype_Mark (SI));
 
-      begin
-         if Denotes_Discriminant (Expr) then
-            Discrim_Scope := Scope (Entity (Expr));
+      if Is_Access_Type (T) then
+         T := Designated_Type (T);
+      end if;
 
-            --  Either we have a reference to one of Typ's discriminants,
+      --  If an index constraint follows a subtype mark in a subtype indication
+      --  then the type or subtype denoted by the subtype mark must not already
+      --  impose an index constraint. The subtype mark must denote either an
+      --  unconstrained array type or an access type whose designated type
+      --  is such an array type... (RM 3.6.1)
 
-            pragma Assert (Discrim_Scope = Typ
+      if Is_Constrained (T) then
+         Error_Msg_N ("array type is already constrained", Subtype_Mark (SI));
+         Constraint_OK := False;
 
-               --  or to the discriminants of the parent type, in the case
-               --  of a derivation of a tagged type with variants.
+      else
+         S := First (Constraints (C));
+         while Present (S) loop
+            Number_Of_Constraints := Number_Of_Constraints + 1;
+            Next (S);
+         end loop;
 
-               or else Discrim_Scope = Etype (Typ)
-               or else Full_View (Discrim_Scope) = Etype (Typ)
+         --  In either case, the index constraint must provide a discrete
+         --  range for each index of the array type and the type of each
+         --  discrete range must be the same as that of the corresponding
+         --  index. (RM 3.6.1)
 
-               --  or same as above for the case where the discriminants
-               --  were declared in Typ's private view.
+         if Number_Of_Constraints /= Number_Dimensions (T) then
+            Error_Msg_NE ("incorrect number of index constraints for }", C, T);
+            Constraint_OK := False;
 
-               or else (Is_Private_Type (Discrim_Scope)
-                        and then Chars (Discrim_Scope) = Chars (Typ))
+         else
+            S := First (Constraints (C));
+            Index := First_Index (T);
+            Analyze (Index);
 
-               --  or else we are deriving from the full view and the
-               --  discriminant is declared in the private entity.
+            --  Apply constraints to each index type
 
-               or else (Is_Private_Type (Typ)
-                         and then Chars (Discrim_Scope) = Chars (Typ))
+            for J in 1 .. Number_Of_Constraints loop
+               Constrain_Index (Index, S, Related_Nod, Related_Id, Suffix, J);
+               Next (Index);
+               Next (S);
+            end loop;
 
-               --  Or we are constrained the corresponding record of a
-               --  synchronized type that completes a private declaration.
+         end if;
+      end if;
 
-               or else (Is_Concurrent_Record_Type (Typ)
-                         and then
-                           Corresponding_Concurrent_Type (Typ) = Discrim_Scope)
+      if No (Def_Id) then
+         Def_Id :=
+           Create_Itype (E_Array_Subtype, Related_Nod, Related_Id, Suffix);
+         Set_Parent (Def_Id, Related_Nod);
 
-               --  or we have a class-wide type, in which case make sure the
-               --  discriminant found belongs to the root type.
-
-               or else (Is_Class_Wide_Type (Typ)
-                         and then Etype (Typ) = Discrim_Scope));
-
-            return True;
-         end if;
-
-         --  In all other cases we have something wrong
+      else
+         Set_Ekind (Def_Id, E_Array_Subtype);
+      end if;
 
-         return False;
-      end Is_Discriminant;
+      Set_Size_Info      (Def_Id,                (T));
+      Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
+      Set_Etype          (Def_Id, Base_Type      (T));
 
-   --  Start of processing for Constrain_Component_Type
+      if Constraint_OK then
+         Set_First_Index (Def_Id, First (Constraints (C)));
+      else
+         Set_First_Index (Def_Id, First_Index (T));
+      end if;
 
-   begin
-      if Nkind (Parent (Comp)) = N_Component_Declaration
-        and then Comes_From_Source (Parent (Comp))
-        and then Comes_From_Source
-          (Subtype_Indication (Component_Definition (Parent (Comp))))
-        and then
-          Is_Entity_Name
-            (Subtype_Indication (Component_Definition (Parent (Comp))))
-      then
-         return Compon_Type;
+      Set_Is_Constrained     (Def_Id, True);
+      Set_Is_Aliased         (Def_Id, Is_Aliased (T));
+      Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
 
-      elsif Is_Array_Type (Compon_Type) then
-         return Build_Constrained_Array_Type (Compon_Type);
+      Set_Is_Private_Composite (Def_Id, Is_Private_Composite (T));
+      Set_Is_Limited_Composite (Def_Id, Is_Limited_Composite (T));
 
-      elsif Has_Discriminants (Compon_Type) then
-         return Build_Constrained_Discriminated_Type (Compon_Type);
+      --  A subtype does not inherit the Packed_Array_Impl_Type of is parent.
+      --  We need to initialize the attribute because if Def_Id is previously
+      --  analyzed through a limited_with clause, it will have the attributes
+      --  of an incomplete type, one of which is an Elist that overlaps the
+      --  Packed_Array_Impl_Type field.
 
-      elsif Is_Access_Type (Compon_Type) then
-         return Build_Constrained_Access_Type (Compon_Type);
+      Set_Packed_Array_Impl_Type (Def_Id, Empty);
 
-      else
-         return Compon_Type;
-      end if;
-   end Constrain_Component_Type;
+      --  Build a freeze node if parent still needs one. Also make sure that
+      --  the Depends_On_Private status is set because the subtype will need
+      --  reprocessing at the time the base type does, and also we must set a
+      --  conditional delay.
 
-   --------------------------
-   -- Constrain_Concurrent --
-   --------------------------
+      Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
+      Conditional_Delay (Def_Id, T);
+   end Constrain_Array;
 
-   --  For concurrent types, the associated record value type carries the same
-   --  discriminants, so when we constrain a concurrent type, we must constrain
-   --  the corresponding record type as well.
+   ------------------------------
+   -- Constrain_Component_Type --
+   ------------------------------
 
-   procedure Constrain_Concurrent
-     (Def_Id      : in out Entity_Id;
-      SI          : Node_Id;
-      Related_Nod : Node_Id;
-      Related_Id  : Entity_Id;
-      Suffix      : Character)
+   function Constrain_Component_Type
+     (Comp            : Entity_Id;
+      Constrained_Typ : Entity_Id;
+      Related_Node    : Node_Id;
+      Typ             : Entity_Id;
+      Constraints     : Elist_Id) return Entity_Id
    is
-      --  Retrieve Base_Type to ensure getting to the concurrent type in the
-      --  case of a private subtype (needed when only doing semantic analysis).
+      Loc         : constant Source_Ptr := Sloc (Constrained_Typ);
+      Compon_Type : constant Entity_Id := Etype (Comp);
 
-      T_Ent : Entity_Id := Base_Type (Entity (Subtype_Mark (SI)));
-      T_Val : Entity_Id;
+      function Build_Constrained_Array_Type
+        (Old_Type : Entity_Id) return Entity_Id;
+      --  If Old_Type is an array type, one of whose indexes is constrained
+      --  by a discriminant, build an Itype whose constraint replaces the
+      --  discriminant with its value in the constraint.
 
-   begin
-      if Is_Access_Type (T_Ent) then
-         T_Ent := Designated_Type (T_Ent);
-      end if;
+      function Build_Constrained_Discriminated_Type
+        (Old_Type : Entity_Id) return Entity_Id;
+      --  Ditto for record components
 
-      T_Val := Corresponding_Record_Type (T_Ent);
+      function Build_Constrained_Access_Type
+        (Old_Type : Entity_Id) return Entity_Id;
+      --  Ditto for access types. Makes use of previous two functions, to
+      --  constrain designated type.
 
-      if Present (T_Val) then
+      function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id;
+      --  T is an array or discriminated type, C is a list of constraints
+      --  that apply to T. This routine builds the constrained subtype.
 
-         if No (Def_Id) then
-            Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
-         end if;
+      function Is_Discriminant (Expr : Node_Id) return Boolean;
+      --  Returns True if Expr is a discriminant
 
-         Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
+      function Get_Discr_Value (Discrim : Entity_Id) return Node_Id;
+      --  Find the value of discriminant Discrim in Constraint
 
-         Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
-         Set_Corresponding_Record_Type (Def_Id,
-           Constrain_Corresponding_Record (Def_Id, T_Val, Related_Nod));
+      -----------------------------------
+      -- Build_Constrained_Access_Type --
+      -----------------------------------
 
-      else
-         --  If there is no associated record, expansion is disabled and this
-         --  is a generic context. Create a subtype in any case, so that
-         --  semantic analysis can proceed.
+      function Build_Constrained_Access_Type
+        (Old_Type : Entity_Id) return Entity_Id
+      is
+         Desig_Type    : constant Entity_Id := Designated_Type (Old_Type);
+         Itype         : Entity_Id;
+         Desig_Subtype : Entity_Id;
+         Scop          : Entity_Id;
 
-         if No (Def_Id) then
-            Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
-         end if;
+      begin
+         --  if the original access type was not embedded in the enclosing
+         --  type definition, there is no need to produce a new access
+         --  subtype. In fact every access type with an explicit constraint
+         --  generates an itype whose scope is the enclosing record.
 
-         Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
-      end if;
-   end Constrain_Concurrent;
+         if not Is_Type (Scope (Old_Type)) then
+            return Old_Type;
 
-   ------------------------------------
-   -- Constrain_Corresponding_Record --
-   ------------------------------------
+         elsif Is_Array_Type (Desig_Type) then
+            Desig_Subtype := Build_Constrained_Array_Type (Desig_Type);
 
-   function Constrain_Corresponding_Record
-     (Prot_Subt   : Entity_Id;
-      Corr_Rec    : Entity_Id;
-      Related_Nod : Node_Id) return Entity_Id
-   is
-      T_Sub : constant Entity_Id :=
-                Create_Itype (E_Record_Subtype, Related_Nod, Corr_Rec, 'C');
+         elsif Has_Discriminants (Desig_Type) then
 
-   begin
-      Set_Etype             (T_Sub, Corr_Rec);
-      Set_Has_Discriminants (T_Sub, Has_Discriminants (Prot_Subt));
-      Set_Is_Constrained    (T_Sub, True);
-      Set_First_Entity      (T_Sub, First_Entity (Corr_Rec));
-      Set_Last_Entity       (T_Sub, Last_Entity  (Corr_Rec));
+            --  This may be an access type to an enclosing record type for
+            --  which we are constructing the constrained components. Return
+            --  the enclosing record subtype. This is not always correct,
+            --  but avoids infinite recursion. ???
 
-      if Has_Discriminants (Prot_Subt) then -- False only if errors.
-         Set_Discriminant_Constraint
-           (T_Sub, Discriminant_Constraint (Prot_Subt));
-         Set_Stored_Constraint_From_Discriminant_Constraint (T_Sub);
-         Create_Constrained_Components
-           (T_Sub, Related_Nod, Corr_Rec, Discriminant_Constraint (T_Sub));
-      end if;
+            Desig_Subtype := Any_Type;
 
-      Set_Depends_On_Private      (T_Sub, Has_Private_Component (T_Sub));
+            for J in reverse 0 .. Scope_Stack.Last loop
+               Scop := Scope_Stack.Table (J).Entity;
 
-      if Ekind (Scope (Prot_Subt)) /= E_Record_Type then
-         Conditional_Delay (T_Sub, Corr_Rec);
+               if Is_Type (Scop)
+                 and then Base_Type (Scop) = Base_Type (Desig_Type)
+               then
+                  Desig_Subtype := Scop;
+               end if;
 
-      else
-         --  This is a component subtype: it will be frozen in the context of
-         --  the enclosing record's init_proc, so that discriminant references
-         --  are resolved to discriminals. (Note: we used to skip freezing
-         --  altogether in that case, which caused errors downstream for
-         --  components of a bit packed array type).
+               exit when not Is_Type (Scop);
+            end loop;
 
-         Set_Has_Delayed_Freeze (T_Sub);
-      end if;
+            if Desig_Subtype = Any_Type then
+               Desig_Subtype :=
+                 Build_Constrained_Discriminated_Type (Desig_Type);
+            end if;
 
-      return T_Sub;
-   end Constrain_Corresponding_Record;
+         else
+            return Old_Type;
+         end if;
 
-   -----------------------
-   -- Constrain_Decimal --
-   -----------------------
+         if Desig_Subtype /= Desig_Type then
 
-   procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id) is
-      T           : constant Entity_Id  := Entity (Subtype_Mark (S));
-      C           : constant Node_Id    := Constraint (S);
-      Loc         : constant Source_Ptr := Sloc (C);
-      Range_Expr  : Node_Id;
-      Digits_Expr : Node_Id;
-      Digits_Val  : Uint;
-      Bound_Val   : Ureal;
+            --  The Related_Node better be here or else we won't be able
+            --  to attach new itypes to a node in the tree.
 
-   begin
-      Set_Ekind (Def_Id, E_Decimal_Fixed_Point_Subtype);
+            pragma Assert (Present (Related_Node));
 
-      if Nkind (C) = N_Range_Constraint then
-         Range_Expr := Range_Expression (C);
-         Digits_Val := Digits_Value (T);
+            Itype := Create_Itype (E_Access_Subtype, Related_Node);
 
-      else
-         pragma Assert (Nkind (C) = N_Digits_Constraint);
+            Set_Etype                    (Itype, Base_Type      (Old_Type));
+            Set_Size_Info                (Itype,                (Old_Type));
+            Set_Directly_Designated_Type (Itype, Desig_Subtype);
+            Set_Depends_On_Private       (Itype, Has_Private_Component
+                                                                (Old_Type));
+            Set_Is_Access_Constant       (Itype, Is_Access_Constant
+                                                                (Old_Type));
 
-         Check_SPARK_Restriction ("digits constraint is not allowed", S);
+            --  The new itype needs freezing when it depends on a not frozen
+            --  type and the enclosing subtype needs freezing.
 
-         Digits_Expr := Digits_Expression (C);
-         Analyze_And_Resolve (Digits_Expr, Any_Integer);
+            if Has_Delayed_Freeze (Constrained_Typ)
+              and then not Is_Frozen (Constrained_Typ)
+            then
+               Conditional_Delay (Itype, Base_Type (Old_Type));
+            end if;
 
-         Check_Digits_Expression (Digits_Expr);
-         Digits_Val := Expr_Value (Digits_Expr);
+            return Itype;
 
-         if Digits_Val > Digits_Value (T) then
-            Error_Msg_N
-               ("digits expression is incompatible with subtype", C);
-            Digits_Val := Digits_Value (T);
+         else
+            return Old_Type;
          end if;
+      end Build_Constrained_Access_Type;
 
-         if Present (Range_Constraint (C)) then
-            Range_Expr := Range_Expression (Range_Constraint (C));
-         else
-            Range_Expr := Empty;
-         end if;
-      end if;
+      ----------------------------------
+      -- Build_Constrained_Array_Type --
+      ----------------------------------
 
-      Set_Etype            (Def_Id, Base_Type        (T));
-      Set_Size_Info        (Def_Id,                  (T));
-      Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
-      Set_Delta_Value      (Def_Id, Delta_Value      (T));
-      Set_Scale_Value      (Def_Id, Scale_Value      (T));
-      Set_Small_Value      (Def_Id, Small_Value      (T));
-      Set_Machine_Radix_10 (Def_Id, Machine_Radix_10 (T));
-      Set_Digits_Value     (Def_Id, Digits_Val);
+      function Build_Constrained_Array_Type
+        (Old_Type : Entity_Id) return Entity_Id
+      is
+         Lo_Expr     : Node_Id;
+         Hi_Expr     : Node_Id;
+         Old_Index   : Node_Id;
+         Range_Node  : Node_Id;
+         Constr_List : List_Id;
 
-      --  Manufacture range from given digits value if no range present
+         Need_To_Create_Itype : Boolean := False;
 
-      if No (Range_Expr) then
-         Bound_Val := (Ureal_10 ** Digits_Val - Ureal_1) * Small_Value (T);
-         Range_Expr :=
-           Make_Range (Loc,
-             Low_Bound =>
-               Convert_To (T, Make_Real_Literal (Loc, (-Bound_Val))),
-             High_Bound =>
-               Convert_To (T, Make_Real_Literal (Loc, Bound_Val)));
-      end if;
+      begin
+         Old_Index := First_Index (Old_Type);
+         while Present (Old_Index) loop
+            Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
 
-      Set_Scalar_Range_For_Subtype (Def_Id, Range_Expr, T);
-      Set_Discrete_RM_Size (Def_Id);
+            if Is_Discriminant (Lo_Expr)
+                 or else
+               Is_Discriminant (Hi_Expr)
+            then
+               Need_To_Create_Itype := True;
+            end if;
 
-      --  Unconditionally delay the freeze, since we cannot set size
-      --  information in all cases correctly until the freeze point.
+            Next_Index (Old_Index);
+         end loop;
 
-      Set_Has_Delayed_Freeze (Def_Id);
-   end Constrain_Decimal;
+         if Need_To_Create_Itype then
+            Constr_List := New_List;
 
-   ----------------------------------
-   -- Constrain_Discriminated_Type --
-   ----------------------------------
+            Old_Index := First_Index (Old_Type);
+            while Present (Old_Index) loop
+               Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
 
-   procedure Constrain_Discriminated_Type
-     (Def_Id      : Entity_Id;
-      S           : Node_Id;
-      Related_Nod : Node_Id;
-      For_Access  : Boolean := False)
-   is
-      E     : constant Entity_Id := Entity (Subtype_Mark (S));
-      T     : Entity_Id;
-      C     : Node_Id;
-      Elist : Elist_Id := New_Elmt_List;
+               if Is_Discriminant (Lo_Expr) then
+                  Lo_Expr := Get_Discr_Value (Lo_Expr);
+               end if;
 
-      procedure Fixup_Bad_Constraint;
-      --  This is called after finding a bad constraint, and after having
-      --  posted an appropriate error message. The mission is to leave the
-      --  entity T in as reasonable state as possible.
+               if Is_Discriminant (Hi_Expr) then
+                  Hi_Expr := Get_Discr_Value (Hi_Expr);
+               end if;
 
-      --------------------------
-      -- Fixup_Bad_Constraint --
-      --------------------------
+               Range_Node :=
+                 Make_Range
+                   (Loc, New_Copy_Tree (Lo_Expr), New_Copy_Tree (Hi_Expr));
 
-      procedure Fixup_Bad_Constraint is
-      begin
-         --  Set a reasonable Ekind for the entity. For an incomplete type,
-         --  we can't do much, but for other types, we can set the proper
-         --  corresponding subtype kind.
+               Append (Range_Node, To => Constr_List);
+
+               Next_Index (Old_Index);
+            end loop;
+
+            return Build_Subtype (Old_Type, Constr_List);
 
-         if Ekind (T) = E_Incomplete_Type then
-            Set_Ekind (Def_Id, Ekind (T));
          else
-            Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
+            return Old_Type;
          end if;
+      end Build_Constrained_Array_Type;
 
-         --  Set Etype to the known type, to reduce chances of cascaded errors
+      ------------------------------------------
+      -- Build_Constrained_Discriminated_Type --
+      ------------------------------------------
 
-         Set_Etype (Def_Id, E);
-         Set_Error_Posted (Def_Id);
-      end Fixup_Bad_Constraint;
+      function Build_Constrained_Discriminated_Type
+        (Old_Type : Entity_Id) return Entity_Id
+      is
+         Expr           : Node_Id;
+         Constr_List    : List_Id;
+         Old_Constraint : Elmt_Id;
 
-   --  Start of processing for Constrain_Discriminated_Type
+         Need_To_Create_Itype : Boolean := False;
 
-   begin
-      C := Constraint (S);
+      begin
+         Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
+         while Present (Old_Constraint) loop
+            Expr := Node (Old_Constraint);
 
-      --  A discriminant constraint is only allowed in a subtype indication,
-      --  after a subtype mark. This subtype mark must denote either a type
-      --  with discriminants, or an access type whose designated type is a
-      --  type with discriminants. A discriminant constraint specifies the
-      --  values of these discriminants (RM 3.7.2(5)).
+            if Is_Discriminant (Expr) then
+               Need_To_Create_Itype := True;
+            end if;
 
-      T := Base_Type (Entity (Subtype_Mark (S)));
+            Next_Elmt (Old_Constraint);
+         end loop;
 
-      if Is_Access_Type (T) then
-         T := Designated_Type (T);
-      end if;
+         if Need_To_Create_Itype then
+            Constr_List := New_List;
 
-      --  Ada 2005 (AI-412): Constrained incomplete subtypes are illegal.
-      --  Avoid generating an error for access-to-incomplete subtypes.
+            Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
+            while Present (Old_Constraint) loop
+               Expr := Node (Old_Constraint);
 
-      if Ada_Version >= Ada_2005
-        and then Ekind (T) = E_Incomplete_Type
-        and then Nkind (Parent (S)) = N_Subtype_Declaration
-        and then not Is_Itype (Def_Id)
-      then
-         --  A little sanity check, emit an error message if the type
-         --  has discriminants to begin with. Type T may be a regular
-         --  incomplete type or imported via a limited with clause.
+               if Is_Discriminant (Expr) then
+                  Expr := Get_Discr_Value (Expr);
+               end if;
+
+               Append (New_Copy_Tree (Expr), To => Constr_List);
+
+               Next_Elmt (Old_Constraint);
+            end loop;
+
+            return Build_Subtype (Old_Type, Constr_List);
 
-         if Has_Discriminants (T)
-           or else (From_Limited_With (T)
-                     and then Present (Non_Limited_View (T))
-                     and then Nkind (Parent (Non_Limited_View (T))) =
-                                               N_Full_Type_Declaration
-                     and then Present (Discriminant_Specifications
-                                         (Parent (Non_Limited_View (T)))))
-         then
-            Error_Msg_N
-              ("(Ada 2005) incomplete subtype may not be constrained", C);
          else
-            Error_Msg_N ("invalid constraint: type has no discriminant", C);
+            return Old_Type;
          end if;
+      end Build_Constrained_Discriminated_Type;
 
-         Fixup_Bad_Constraint;
-         return;
+      -------------------
+      -- Build_Subtype --
+      -------------------
 
-      --  Check that the type has visible discriminants. The type may be
-      --  a private type with unknown discriminants whose full view has
-      --  discriminants which are invisible.
+      function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id is
+         Indic       : Node_Id;
+         Subtyp_Decl : Node_Id;
+         Def_Id      : Entity_Id;
+         Btyp        : Entity_Id := Base_Type (T);
 
-      elsif not Has_Discriminants (T)
-        or else
-          (Has_Unknown_Discriminants (T)
-             and then Is_Private_Type (T))
-      then
-         Error_Msg_N ("invalid constraint: type has no discriminant", C);
-         Fixup_Bad_Constraint;
-         return;
+      begin
+         --  The Related_Node better be here or else we won't be able to
+         --  attach new itypes to a node in the tree.
 
-      elsif Is_Constrained (E)
-        or else (Ekind (E) = E_Class_Wide_Subtype
-                  and then Present (Discriminant_Constraint (E)))
-      then
-         Error_Msg_N ("type is already constrained", Subtype_Mark (S));
-         Fixup_Bad_Constraint;
-         return;
-      end if;
+         pragma Assert (Present (Related_Node));
 
-      --  T may be an unconstrained subtype (e.g. a generic actual).
-      --  Constraint applies to the base type.
+         --  If the view of the component's type is incomplete or private
+         --  with unknown discriminants, then the constraint must be applied
+         --  to the full type.
 
-      T := Base_Type (T);
+         if Has_Unknown_Discriminants (Btyp)
+           and then Present (Underlying_Type (Btyp))
+         then
+            Btyp := Underlying_Type (Btyp);
+         end if;
 
-      Elist := Build_Discriminant_Constraints (T, S);
+         Indic :=
+           Make_Subtype_Indication (Loc,
+             Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
+             Constraint   => Make_Index_Or_Discriminant_Constraint (Loc, C));
 
-      --  If the list returned was empty we had an error in building the
-      --  discriminant constraint. We have also already signalled an error
-      --  in the incomplete type case
+         Def_Id := Create_Itype (Ekind (T), Related_Node);
 
-      if Is_Empty_Elmt_List (Elist) then
-         Fixup_Bad_Constraint;
-         return;
-      end if;
+         Subtyp_Decl :=
+           Make_Subtype_Declaration (Loc,
+             Defining_Identifier => Def_Id,
+             Subtype_Indication  => Indic);
 
-      Build_Discriminated_Subtype (T, Def_Id, Elist, Related_Nod, For_Access);
-   end Constrain_Discriminated_Type;
+         Set_Parent (Subtyp_Decl, Parent (Related_Node));
 
-   ---------------------------
-   -- Constrain_Enumeration --
-   ---------------------------
+         --  Itypes must be analyzed with checks off (see package Itypes)
 
-   procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id) is
-      T : constant Entity_Id := Entity (Subtype_Mark (S));
-      C : constant Node_Id   := Constraint (S);
+         Analyze (Subtyp_Decl, Suppress => All_Checks);
 
-   begin
-      Set_Ekind (Def_Id, E_Enumeration_Subtype);
+         return Def_Id;
+      end Build_Subtype;
 
-      Set_First_Literal     (Def_Id, First_Literal (Base_Type (T)));
+      ---------------------
+      -- Get_Discr_Value --
+      ---------------------
 
-      Set_Etype             (Def_Id, Base_Type         (T));
-      Set_Size_Info         (Def_Id,                   (T));
-      Set_First_Rep_Item    (Def_Id, First_Rep_Item    (T));
-      Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
+      function Get_Discr_Value (Discrim : Entity_Id) return Node_Id is
+         D : Entity_Id;
+         E : Elmt_Id;
 
-      Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
+      begin
+         --  The discriminant may be declared for the type, in which case we
+         --  find it by iterating over the list of discriminants. If the
+         --  discriminant is inherited from a parent type, it appears as the
+         --  corresponding discriminant of the current type. This will be the
+         --  case when constraining an inherited component whose constraint is
+         --  given by a discriminant of the parent.
 
-      Set_Discrete_RM_Size (Def_Id);
-   end Constrain_Enumeration;
+         D := First_Discriminant (Typ);
+         E := First_Elmt (Constraints);
 
-   ----------------------
-   -- Constrain_Float --
-   ----------------------
+         while Present (D) loop
+            if D = Entity (Discrim)
+              or else D = CR_Discriminant (Entity (Discrim))
+              or else Corresponding_Discriminant (D) = Entity (Discrim)
+            then
+               return Node (E);
+            end if;
 
-   procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id) is
-      T    : constant Entity_Id := Entity (Subtype_Mark (S));
-      C    : Node_Id;
-      D    : Node_Id;
-      Rais : Node_Id;
+            Next_Discriminant (D);
+            Next_Elmt (E);
+         end loop;
 
-   begin
-      Set_Ekind (Def_Id, E_Floating_Point_Subtype);
+         --  The Corresponding_Discriminant mechanism is incomplete, because
+         --  the correspondence between new and old discriminants is not one
+         --  to one: one new discriminant can constrain several old ones. In
+         --  that case, scan sequentially the stored_constraint, the list of
+         --  discriminants of the parents, and the constraints.
 
-      Set_Etype          (Def_Id, Base_Type      (T));
-      Set_Size_Info      (Def_Id,                (T));
-      Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
+         --  Previous code checked for the present of the Stored_Constraint
+         --  list for the derived type, but did not use it at all. Should it
+         --  be present when the component is a discriminated task type?
 
-      --  Process the constraint
+         if Is_Derived_Type (Typ)
+           and then Scope (Entity (Discrim)) = Etype (Typ)
+         then
+            D := First_Discriminant (Etype (Typ));
+            E := First_Elmt (Constraints);
+            while Present (D) loop
+               if D = Entity (Discrim) then
+                  return Node (E);
+               end if;
 
-      C := Constraint (S);
+               Next_Discriminant (D);
+               Next_Elmt (E);
+            end loop;
+         end if;
 
-      --  Digits constraint present
+         --  Something is wrong if we did not find the value
 
-      if Nkind (C) = N_Digits_Constraint then
+         raise Program_Error;
+      end Get_Discr_Value;
 
-         Check_SPARK_Restriction ("digits constraint is not allowed", S);
-         Check_Restriction (No_Obsolescent_Features, C);
+      ---------------------
+      -- Is_Discriminant --
+      ---------------------
 
-         if Warn_On_Obsolescent_Feature then
-            Error_Msg_N
-              ("subtype digits constraint is an " &
-               "obsolescent feature (RM J.3(8))?j?", C);
-         end if;
+      function Is_Discriminant (Expr : Node_Id) return Boolean is
+         Discrim_Scope : Entity_Id;
 
-         D := Digits_Expression (C);
-         Analyze_And_Resolve (D, Any_Integer);
-         Check_Digits_Expression (D);
-         Set_Digits_Value (Def_Id, Expr_Value (D));
+      begin
+         if Denotes_Discriminant (Expr) then
+            Discrim_Scope := Scope (Entity (Expr));
 
-         --  Check that digits value is in range. Obviously we can do this
-         --  at compile time, but it is strictly a runtime check, and of
-         --  course there is an ACVC test that checks this.
+            --  Either we have a reference to one of Typ's discriminants,
 
-         if Digits_Value (Def_Id) > Digits_Value (T) then
-            Error_Msg_Uint_1 := Digits_Value (T);
-            Error_Msg_N ("??digits value is too large, maximum is ^", D);
-            Rais :=
-              Make_Raise_Constraint_Error (Sloc (D),
-                Reason => CE_Range_Check_Failed);
-            Insert_Action (Declaration_Node (Def_Id), Rais);
-         end if;
+            pragma Assert (Discrim_Scope = Typ
 
-         C := Range_Constraint (C);
+               --  or to the discriminants of the parent type, in the case
+               --  of a derivation of a tagged type with variants.
 
-      --  No digits constraint present
+               or else Discrim_Scope = Etype (Typ)
+               or else Full_View (Discrim_Scope) = Etype (Typ)
 
-      else
-         Set_Digits_Value (Def_Id, Digits_Value (T));
-      end if;
+               --  or same as above for the case where the discriminants
+               --  were declared in Typ's private view.
 
-      --  Range constraint present
+               or else (Is_Private_Type (Discrim_Scope)
+                         and then Chars (Discrim_Scope) = Chars (Typ))
 
-      if Nkind (C) = N_Range_Constraint then
-         Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
+               --  or else we are deriving from the full view and the
+               --  discriminant is declared in the private entity.
 
-      --  No range constraint present
+               or else (Is_Private_Type (Typ)
+                         and then Chars (Discrim_Scope) = Chars (Typ))
 
-      else
-         pragma Assert (No (C));
-         Set_Scalar_Range (Def_Id, Scalar_Range (T));
-      end if;
+               --  Or we are constrained the corresponding record of a
+               --  synchronized type that completes a private declaration.
 
-      Set_Is_Constrained (Def_Id);
-   end Constrain_Float;
+               or else (Is_Concurrent_Record_Type (Typ)
+                         and then
+                           Corresponding_Concurrent_Type (Typ) = Discrim_Scope)
 
-   ---------------------
-   -- Constrain_Index --
-   ---------------------
+               --  or we have a class-wide type, in which case make sure the
+               --  discriminant found belongs to the root type.
 
-   procedure Constrain_Index
-     (Index        : Node_Id;
-      S            : Node_Id;
-      Related_Nod  : Node_Id;
-      Related_Id   : Entity_Id;
-      Suffix       : Character;
-      Suffix_Index : Nat)
-   is
-      Def_Id : Entity_Id;
-      R      : Node_Id := Empty;
-      T      : constant Entity_Id := Etype (Index);
+               or else (Is_Class_Wide_Type (Typ)
+                         and then Etype (Typ) = Discrim_Scope));
+
+            return True;
+         end if;
+
+         --  In all other cases we have something wrong
+
+         return False;
+      end Is_Discriminant;
+
+   --  Start of processing for Constrain_Component_Type
 
    begin
-      if Nkind (S) = N_Range
-        or else
-          (Nkind (S) = N_Attribute_Reference
-            and then Attribute_Name (S) = Name_Range)
+      if Nkind (Parent (Comp)) = N_Component_Declaration
+        and then Comes_From_Source (Parent (Comp))
+        and then Comes_From_Source
+          (Subtype_Indication (Component_Definition (Parent (Comp))))
+        and then
+          Is_Entity_Name
+            (Subtype_Indication (Component_Definition (Parent (Comp))))
       then
-         --  A Range attribute will be transformed into N_Range by Resolve
+         return Compon_Type;
 
-         Analyze (S);
-         Set_Etype (S, T);
-         R := S;
+      elsif Is_Array_Type (Compon_Type) then
+         return Build_Constrained_Array_Type (Compon_Type);
 
-         Process_Range_Expr_In_Decl (R, T);
+      elsif Has_Discriminants (Compon_Type) then
+         return Build_Constrained_Discriminated_Type (Compon_Type);
 
-         if not Error_Posted (S)
-           and then
-             (Nkind (S) /= N_Range
-               or else not Covers (T, (Etype (Low_Bound (S))))
-               or else not Covers (T, (Etype (High_Bound (S)))))
-         then
-            if Base_Type (T) /= Any_Type
-              and then Etype (Low_Bound (S)) /= Any_Type
-              and then Etype (High_Bound (S)) /= Any_Type
-            then
-               Error_Msg_N ("range expected", S);
-            end if;
-         end if;
+      elsif Is_Access_Type (Compon_Type) then
+         return Build_Constrained_Access_Type (Compon_Type);
 
-      elsif Nkind (S) = N_Subtype_Indication then
+      else
+         return Compon_Type;
+      end if;
+   end Constrain_Component_Type;
 
-         --  The parser has verified that this is a discrete indication
+   --------------------------
+   -- Constrain_Concurrent --
+   --------------------------
 
-         Resolve_Discrete_Subtype_Indication (S, T);
-         Bad_Predicated_Subtype_Use
-           ("subtype& has predicate, not allowed in index constraint",
-            S, Entity (Subtype_Mark (S)));
+   --  For concurrent types, the associated record value type carries the same
+   --  discriminants, so when we constrain a concurrent type, we must constrain
+   --  the corresponding record type as well.
 
-         R := Range_Expression (Constraint (S));
+   procedure Constrain_Concurrent
+     (Def_Id      : in out Entity_Id;
+      SI          : Node_Id;
+      Related_Nod : Node_Id;
+      Related_Id  : Entity_Id;
+      Suffix      : Character)
+   is
+      --  Retrieve Base_Type to ensure getting to the concurrent type in the
+      --  case of a private subtype (needed when only doing semantic analysis).
 
-         --  Capture values of bounds and generate temporaries for them if
-         --  needed, since checks may cause duplication of the expressions
-         --  which must not be reevaluated.
+      T_Ent : Entity_Id := Base_Type (Entity (Subtype_Mark (SI)));
+      T_Val : Entity_Id;
 
-         --  The forced evaluation removes side effects from expressions, which
-         --  should occur also in GNATprove mode. Otherwise, we end up with
-         --  unexpected insertions of actions at places where this is not
-         --  supposed to occur, e.g. on default parameters of a call.
+   begin
+      if Is_Access_Type (T_Ent) then
+         T_Ent := Designated_Type (T_Ent);
+      end if;
 
-         if Expander_Active or GNATprove_Mode then
-            Force_Evaluation (Low_Bound (R));
-            Force_Evaluation (High_Bound (R));
-         end if;
+      T_Val := Corresponding_Record_Type (T_Ent);
 
-      elsif Nkind (S) = N_Discriminant_Association then
+      if Present (T_Val) then
 
-         --  Syntactically valid in subtype indication
+         if No (Def_Id) then
+            Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
+         end if;
 
-         Error_Msg_N ("invalid index constraint", S);
-         Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
-         return;
+         Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
 
-      --  Subtype_Mark case, no anonymous subtypes to construct
+         Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
+         Set_Corresponding_Record_Type (Def_Id,
+           Constrain_Corresponding_Record (Def_Id, T_Val, Related_Nod));
 
       else
-         Analyze (S);
-
-         if Is_Entity_Name (S) then
-            if not Is_Type (Entity (S)) then
-               Error_Msg_N ("expect subtype mark for index constraint", S);
-
-            elsif Base_Type (Entity (S)) /= Base_Type (T) then
-               Wrong_Type (S, Base_Type (T));
-
-            --  Check error of subtype with predicate in index constraint
-
-            else
-               Bad_Predicated_Subtype_Use
-                 ("subtype& has predicate, not allowed in index constraint",
-                  S, Entity (S));
-            end if;
-
-            return;
+         --  If there is no associated record, expansion is disabled and this
+         --  is a generic context. Create a subtype in any case, so that
+         --  semantic analysis can proceed.
 
-         else
-            Error_Msg_N ("invalid index constraint", S);
-            Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
-            return;
+         if No (Def_Id) then
+            Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
          end if;
-      end if;
-
-      Def_Id :=
-        Create_Itype (E_Void, Related_Nod, Related_Id, Suffix, Suffix_Index);
-
-      Set_Etype (Def_Id, Base_Type (T));
-
-      if Is_Modular_Integer_Type (T) then
-         Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
-
-      elsif Is_Integer_Type (T) then
-         Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
 
-      else
-         Set_Ekind (Def_Id, E_Enumeration_Subtype);
-         Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
-         Set_First_Literal     (Def_Id, First_Literal (T));
+         Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
       end if;
+   end Constrain_Concurrent;
 
-      Set_Size_Info      (Def_Id,                (T));
-      Set_RM_Size        (Def_Id, RM_Size        (T));
-      Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
+   ------------------------------------
+   -- Constrain_Corresponding_Record --
+   ------------------------------------
 
-      Set_Scalar_Range   (Def_Id, R);
+   function Constrain_Corresponding_Record
+     (Prot_Subt   : Entity_Id;
+      Corr_Rec    : Entity_Id;
+      Related_Nod : Node_Id) return Entity_Id
+   is
+      T_Sub : constant Entity_Id :=
+                Create_Itype (E_Record_Subtype, Related_Nod, Corr_Rec, 'C');
 
-      Set_Etype (S, Def_Id);
-      Set_Discrete_RM_Size (Def_Id);
-   end Constrain_Index;
+   begin
+      Set_Etype             (T_Sub, Corr_Rec);
+      Set_Has_Discriminants (T_Sub, Has_Discriminants (Prot_Subt));
+      Set_Is_Constrained    (T_Sub, True);
+      Set_First_Entity      (T_Sub, First_Entity (Corr_Rec));
+      Set_Last_Entity       (T_Sub, Last_Entity  (Corr_Rec));
 
-   -----------------------
-   -- Constrain_Integer --
-   -----------------------
+      if Has_Discriminants (Prot_Subt) then -- False only if errors.
+         Set_Discriminant_Constraint
+           (T_Sub, Discriminant_Constraint (Prot_Subt));
+         Set_Stored_Constraint_From_Discriminant_Constraint (T_Sub);
+         Create_Constrained_Components
+           (T_Sub, Related_Nod, Corr_Rec, Discriminant_Constraint (T_Sub));
+      end if;
 
-   procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id) is
-      T : constant Entity_Id := Entity (Subtype_Mark (S));
-      C : constant Node_Id   := Constraint (S);
+      Set_Depends_On_Private      (T_Sub, Has_Private_Component (T_Sub));
 
-   begin
-      Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
+      if Ekind (Scope (Prot_Subt)) /= E_Record_Type then
+         Conditional_Delay (T_Sub, Corr_Rec);
 
-      if Is_Modular_Integer_Type (T) then
-         Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
       else
-         Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
+         --  This is a component subtype: it will be frozen in the context of
+         --  the enclosing record's init_proc, so that discriminant references
+         --  are resolved to discriminals. (Note: we used to skip freezing
+         --  altogether in that case, which caused errors downstream for
+         --  components of a bit packed array type).
+
+         Set_Has_Delayed_Freeze (T_Sub);
       end if;
 
-      Set_Etype            (Def_Id, Base_Type      (T));
-      Set_Size_Info        (Def_Id,                (T));
-      Set_First_Rep_Item   (Def_Id, First_Rep_Item (T));
-      Set_Discrete_RM_Size (Def_Id);
-   end Constrain_Integer;
+      return T_Sub;
+   end Constrain_Corresponding_Record;
 
-   ------------------------------
-   -- Constrain_Ordinary_Fixed --
-   ------------------------------
+   -----------------------
+   -- Constrain_Decimal --
+   -----------------------
 
-   procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id) is
-      T    : constant Entity_Id := Entity (Subtype_Mark (S));
-      C    : Node_Id;
-      D    : Node_Id;
-      Rais : Node_Id;
+   procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id) is
+      T           : constant Entity_Id  := Entity (Subtype_Mark (S));
+      C           : constant Node_Id    := Constraint (S);
+      Loc         : constant Source_Ptr := Sloc (C);
+      Range_Expr  : Node_Id;
+      Digits_Expr : Node_Id;
+      Digits_Val  : Uint;
+      Bound_Val   : Ureal;
 
    begin
-      Set_Ekind          (Def_Id, E_Ordinary_Fixed_Point_Subtype);
-      Set_Etype          (Def_Id, Base_Type      (T));
-      Set_Size_Info      (Def_Id,                (T));
-      Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
-      Set_Small_Value    (Def_Id, Small_Value    (T));
+      Set_Ekind (Def_Id, E_Decimal_Fixed_Point_Subtype);
 
-      --  Process the constraint
+      if Nkind (C) = N_Range_Constraint then
+         Range_Expr := Range_Expression (C);
+         Digits_Val := Digits_Value (T);
 
-      C := Constraint (S);
+      else
+         pragma Assert (Nkind (C) = N_Digits_Constraint);
 
-      --  Delta constraint present
+         Check_SPARK_05_Restriction ("digits constraint is not allowed", S);
 
-      if Nkind (C) = N_Delta_Constraint then
+         Digits_Expr := Digits_Expression (C);
+         Analyze_And_Resolve (Digits_Expr, Any_Integer);
 
-         Check_SPARK_Restriction ("delta constraint is not allowed", S);
-         Check_Restriction (No_Obsolescent_Features, C);
+         Check_Digits_Expression (Digits_Expr);
+         Digits_Val := Expr_Value (Digits_Expr);
 
-         if Warn_On_Obsolescent_Feature then
-            Error_Msg_S
-              ("subtype delta constraint is an " &
-               "obsolescent feature (RM J.3(7))?j?");
+         if Digits_Val > Digits_Value (T) then
+            Error_Msg_N
+               ("digits expression is incompatible with subtype", C);
+            Digits_Val := Digits_Value (T);
          end if;
 
-         D := Delta_Expression (C);
-         Analyze_And_Resolve (D, Any_Real);
-         Check_Delta_Expression (D);
-         Set_Delta_Value (Def_Id, Expr_Value_R (D));
-
-         --  Check that delta value is in range. Obviously we can do this
-         --  at compile time, but it is strictly a runtime check, and of
-         --  course there is an ACVC test that checks this.
-
-         if Delta_Value (Def_Id) < Delta_Value (T) then
-            Error_Msg_N ("??delta value is too small", D);
-            Rais :=
-              Make_Raise_Constraint_Error (Sloc (D),
-                Reason => CE_Range_Check_Failed);
-            Insert_Action (Declaration_Node (Def_Id), Rais);
+         if Present (Range_Constraint (C)) then
+            Range_Expr := Range_Expression (Range_Constraint (C));
+         else
+            Range_Expr := Empty;
          end if;
-
-         C := Range_Constraint (C);
-
-      --  No delta constraint present
-
-      else
-         Set_Delta_Value (Def_Id, Delta_Value (T));
       end if;
 
-      --  Range constraint present
-
-      if Nkind (C) = N_Range_Constraint then
-         Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
-
-      --  No range constraint present
+      Set_Etype            (Def_Id, Base_Type        (T));
+      Set_Size_Info        (Def_Id,                  (T));
+      Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
+      Set_Delta_Value      (Def_Id, Delta_Value      (T));
+      Set_Scale_Value      (Def_Id, Scale_Value      (T));
+      Set_Small_Value      (Def_Id, Small_Value      (T));
+      Set_Machine_Radix_10 (Def_Id, Machine_Radix_10 (T));
+      Set_Digits_Value     (Def_Id, Digits_Val);
 
-      else
-         pragma Assert (No (C));
-         Set_Scalar_Range (Def_Id, Scalar_Range (T));
+      --  Manufacture range from given digits value if no range present
 
+      if No (Range_Expr) then
+         Bound_Val := (Ureal_10 ** Digits_Val - Ureal_1) * Small_Value (T);
+         Range_Expr :=
+           Make_Range (Loc,
+             Low_Bound =>
+               Convert_To (T, Make_Real_Literal (Loc, (-Bound_Val))),
+             High_Bound =>
+               Convert_To (T, Make_Real_Literal (Loc, Bound_Val)));
       end if;
 
+      Set_Scalar_Range_For_Subtype (Def_Id, Range_Expr, T);
       Set_Discrete_RM_Size (Def_Id);
 
       --  Unconditionally delay the freeze, since we cannot set size
       --  information in all cases correctly until the freeze point.
 
       Set_Has_Delayed_Freeze (Def_Id);
-   end Constrain_Ordinary_Fixed;
+   end Constrain_Decimal;
 
-   -----------------------
-   -- Contain_Interface --
-   -----------------------
+   ----------------------------------
+   -- Constrain_Discriminated_Type --
+   ----------------------------------
 
-   function Contain_Interface
-     (Iface  : Entity_Id;
-      Ifaces : Elist_Id) return Boolean
+   procedure Constrain_Discriminated_Type
+     (Def_Id      : Entity_Id;
+      S           : Node_Id;
+      Related_Nod : Node_Id;
+      For_Access  : Boolean := False)
    is
-      Iface_Elmt : Elmt_Id;
+      E     : constant Entity_Id := Entity (Subtype_Mark (S));
+      T     : Entity_Id;
+      C     : Node_Id;
+      Elist : Elist_Id := New_Elmt_List;
 
-   begin
-      if Present (Ifaces) then
-         Iface_Elmt := First_Elmt (Ifaces);
-         while Present (Iface_Elmt) loop
-            if Node (Iface_Elmt) = Iface then
-               return True;
-            end if;
+      procedure Fixup_Bad_Constraint;
+      --  This is called after finding a bad constraint, and after having
+      --  posted an appropriate error message. The mission is to leave the
+      --  entity T in as reasonable state as possible.
 
-            Next_Elmt (Iface_Elmt);
-         end loop;
-      end if;
+      --------------------------
+      -- Fixup_Bad_Constraint --
+      --------------------------
 
-      return False;
-   end Contain_Interface;
+      procedure Fixup_Bad_Constraint is
+      begin
+         --  Set a reasonable Ekind for the entity. For an incomplete type,
+         --  we can't do much, but for other types, we can set the proper
+         --  corresponding subtype kind.
 
-   ---------------------------
-   -- Convert_Scalar_Bounds --
-   ---------------------------
+         if Ekind (T) = E_Incomplete_Type then
+            Set_Ekind (Def_Id, Ekind (T));
+         else
+            Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
+         end if;
 
-   procedure Convert_Scalar_Bounds
-     (N            : Node_Id;
-      Parent_Type  : Entity_Id;
-      Derived_Type : Entity_Id;
-      Loc          : Source_Ptr)
-   is
-      Implicit_Base : constant Entity_Id := Base_Type (Derived_Type);
+         --  Set Etype to the known type, to reduce chances of cascaded errors
 
-      Lo  : Node_Id;
-      Hi  : Node_Id;
-      Rng : Node_Id;
+         Set_Etype (Def_Id, E);
+         Set_Error_Posted (Def_Id);
+      end Fixup_Bad_Constraint;
+
+   --  Start of processing for Constrain_Discriminated_Type
 
    begin
-      --  Defend against previous errors
+      C := Constraint (S);
 
-      if No (Scalar_Range (Derived_Type)) then
-         Check_Error_Detected;
-         return;
-      end if;
+      --  A discriminant constraint is only allowed in a subtype indication,
+      --  after a subtype mark. This subtype mark must denote either a type
+      --  with discriminants, or an access type whose designated type is a
+      --  type with discriminants. A discriminant constraint specifies the
+      --  values of these discriminants (RM 3.7.2(5)).
 
-      Lo := Build_Scalar_Bound
-              (Type_Low_Bound (Derived_Type),
-               Parent_Type, Implicit_Base);
+      T := Base_Type (Entity (Subtype_Mark (S)));
 
-      Hi := Build_Scalar_Bound
-              (Type_High_Bound (Derived_Type),
-               Parent_Type, Implicit_Base);
+      if Is_Access_Type (T) then
+         T := Designated_Type (T);
+      end if;
 
-      Rng :=
-        Make_Range (Loc,
-          Low_Bound  => Lo,
-          High_Bound => Hi);
+      --  Ada 2005 (AI-412): Constrained incomplete subtypes are illegal.
+      --  Avoid generating an error for access-to-incomplete subtypes.
 
-      Set_Includes_Infinities (Rng, Has_Infinities (Derived_Type));
+      if Ada_Version >= Ada_2005
+        and then Ekind (T) = E_Incomplete_Type
+        and then Nkind (Parent (S)) = N_Subtype_Declaration
+        and then not Is_Itype (Def_Id)
+      then
+         --  A little sanity check, emit an error message if the type
+         --  has discriminants to begin with. Type T may be a regular
+         --  incomplete type or imported via a limited with clause.
 
-      Set_Parent (Rng, N);
-      Set_Scalar_Range (Derived_Type, Rng);
+         if Has_Discriminants (T)
+           or else (From_Limited_With (T)
+                     and then Present (Non_Limited_View (T))
+                     and then Nkind (Parent (Non_Limited_View (T))) =
+                                               N_Full_Type_Declaration
+                     and then Present (Discriminant_Specifications
+                                         (Parent (Non_Limited_View (T)))))
+         then
+            Error_Msg_N
+              ("(Ada 2005) incomplete subtype may not be constrained", C);
+         else
+            Error_Msg_N ("invalid constraint: type has no discriminant", C);
+         end if;
 
-      --  Analyze the bounds
+         Fixup_Bad_Constraint;
+         return;
 
-      Analyze_And_Resolve (Lo, Implicit_Base);
-      Analyze_And_Resolve (Hi, Implicit_Base);
+      --  Check that the type has visible discriminants. The type may be
+      --  a private type with unknown discriminants whose full view has
+      --  discriminants which are invisible.
 
-      --  Analyze the range itself, except that we do not analyze it if
-      --  the bounds are real literals, and we have a fixed-point type.
-      --  The reason for this is that we delay setting the bounds in this
-      --  case till we know the final Small and Size values (see circuit
-      --  in Freeze.Freeze_Fixed_Point_Type for further details).
+      elsif not Has_Discriminants (T)
+        or else
+          (Has_Unknown_Discriminants (T)
+             and then Is_Private_Type (T))
+      then
+         Error_Msg_N ("invalid constraint: type has no discriminant", C);
+         Fixup_Bad_Constraint;
+         return;
 
-      if Is_Fixed_Point_Type (Parent_Type)
-        and then Nkind (Lo) = N_Real_Literal
-        and then Nkind (Hi) = N_Real_Literal
+      elsif Is_Constrained (E)
+        or else (Ekind (E) = E_Class_Wide_Subtype
+                  and then Present (Discriminant_Constraint (E)))
       then
+         Error_Msg_N ("type is already constrained", Subtype_Mark (S));
+         Fixup_Bad_Constraint;
          return;
+      end if;
 
-      --  Here we do the analysis of the range
+      --  T may be an unconstrained subtype (e.g. a generic actual).
+      --  Constraint applies to the base type.
 
-      --  Note: we do this manually, since if we do a normal Analyze and
-      --  Resolve call, there are problems with the conversions used for
-      --  the derived type range.
+      T := Base_Type (T);
 
-      else
-         Set_Etype    (Rng, Implicit_Base);
-         Set_Analyzed (Rng, True);
+      Elist := Build_Discriminant_Constraints (T, S);
+
+      --  If the list returned was empty we had an error in building the
+      --  discriminant constraint. We have also already signalled an error
+      --  in the incomplete type case
+
+      if Is_Empty_Elmt_List (Elist) then
+         Fixup_Bad_Constraint;
+         return;
       end if;
-   end Convert_Scalar_Bounds;
 
-   -------------------
-   -- Copy_And_Swap --
-   -------------------
+      Build_Discriminated_Subtype (T, Def_Id, Elist, Related_Nod, For_Access);
+   end Constrain_Discriminated_Type;
+
+   ---------------------------
+   -- Constrain_Enumeration --
+   ---------------------------
+
+   procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id) is
+      T : constant Entity_Id := Entity (Subtype_Mark (S));
+      C : constant Node_Id   := Constraint (S);
 
-   procedure Copy_And_Swap (Priv, Full : Entity_Id) is
    begin
-      --  Initialize new full declaration entity by copying the pertinent
-      --  fields of the corresponding private declaration entity.
+      Set_Ekind (Def_Id, E_Enumeration_Subtype);
 
-      --  We temporarily set Ekind to a value appropriate for a type to
-      --  avoid assert failures in Einfo from checking for setting type
-      --  attributes on something that is not a type. Ekind (Priv) is an
-      --  appropriate choice, since it allowed the attributes to be set
-      --  in the first place. This Ekind value will be modified later.
+      Set_First_Literal     (Def_Id, First_Literal (Base_Type (T)));
 
-      Set_Ekind (Full, Ekind (Priv));
+      Set_Etype             (Def_Id, Base_Type         (T));
+      Set_Size_Info         (Def_Id,                   (T));
+      Set_First_Rep_Item    (Def_Id, First_Rep_Item    (T));
+      Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
 
-      --  Also set Etype temporarily to Any_Type, again, in the absence
-      --  of errors, it will be properly reset, and if there are errors,
-      --  then we want a value of Any_Type to remain.
+      Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
 
-      Set_Etype (Full, Any_Type);
+      Set_Discrete_RM_Size (Def_Id);
+   end Constrain_Enumeration;
 
-      --  Now start copying attributes
+   ----------------------
+   -- Constrain_Float --
+   ----------------------
 
-      Set_Has_Discriminants          (Full, Has_Discriminants       (Priv));
+   procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id) is
+      T    : constant Entity_Id := Entity (Subtype_Mark (S));
+      C    : Node_Id;
+      D    : Node_Id;
+      Rais : Node_Id;
 
-      if Has_Discriminants (Full) then
-         Set_Discriminant_Constraint (Full, Discriminant_Constraint (Priv));
-         Set_Stored_Constraint       (Full, Stored_Constraint       (Priv));
-      end if;
+   begin
+      Set_Ekind (Def_Id, E_Floating_Point_Subtype);
 
-      Set_First_Rep_Item             (Full, First_Rep_Item          (Priv));
-      Set_Homonym                    (Full, Homonym                 (Priv));
-      Set_Is_Immediately_Visible     (Full, Is_Immediately_Visible  (Priv));
-      Set_Is_Public                  (Full, Is_Public               (Priv));
-      Set_Is_Pure                    (Full, Is_Pure                 (Priv));
-      Set_Is_Tagged_Type             (Full, Is_Tagged_Type          (Priv));
-      Set_Has_Pragma_Unmodified      (Full, Has_Pragma_Unmodified   (Priv));
-      Set_Has_Pragma_Unreferenced    (Full, Has_Pragma_Unreferenced (Priv));
-      Set_Has_Pragma_Unreferenced_Objects
-                                     (Full, Has_Pragma_Unreferenced_Objects
-                                                                    (Priv));
+      Set_Etype          (Def_Id, Base_Type      (T));
+      Set_Size_Info      (Def_Id,                (T));
+      Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
 
-      Conditional_Delay              (Full,                          Priv);
+      --  Process the constraint
 
-      if Is_Tagged_Type (Full) then
-         Set_Direct_Primitive_Operations (Full,
-           Direct_Primitive_Operations (Priv));
+      C := Constraint (S);
 
-         if Is_Base_Type (Priv) then
-            Set_Class_Wide_Type      (Full, Class_Wide_Type         (Priv));
-         end if;
-      end if;
+      --  Digits constraint present
 
-      Set_Is_Volatile                (Full, Is_Volatile             (Priv));
-      Set_Treat_As_Volatile          (Full, Treat_As_Volatile       (Priv));
-      Set_Scope                      (Full, Scope                   (Priv));
-      Set_Next_Entity                (Full, Next_Entity             (Priv));
-      Set_First_Entity               (Full, First_Entity            (Priv));
-      Set_Last_Entity                (Full, Last_Entity             (Priv));
+      if Nkind (C) = N_Digits_Constraint then
 
-      --  If access types have been recorded for later handling, keep them in
-      --  the full view so that they get handled when the full view freeze
-      --  node is expanded.
+         Check_SPARK_05_Restriction ("digits constraint is not allowed", S);
+         Check_Restriction (No_Obsolescent_Features, C);
 
-      if Present (Freeze_Node (Priv))
-        and then Present (Access_Types_To_Process (Freeze_Node (Priv)))
-      then
-         Ensure_Freeze_Node (Full);
-         Set_Access_Types_To_Process
-           (Freeze_Node (Full),
-            Access_Types_To_Process (Freeze_Node (Priv)));
-      end if;
+         if Warn_On_Obsolescent_Feature then
+            Error_Msg_N
+              ("subtype digits constraint is an " &
+               "obsolescent feature (RM J.3(8))?j?", C);
+         end if;
 
-      --  Swap the two entities. Now Private is the full type entity and Full
-      --  is the private one. They will be swapped back at the end of the
-      --  private part. This swapping ensures that the entity that is visible
-      --  in the private part is the full declaration.
+         D := Digits_Expression (C);
+         Analyze_And_Resolve (D, Any_Integer);
+         Check_Digits_Expression (D);
+         Set_Digits_Value (Def_Id, Expr_Value (D));
 
-      Exchange_Entities (Priv, Full);
-      Append_Entity (Full, Scope (Full));
-   end Copy_And_Swap;
+         --  Check that digits value is in range. Obviously we can do this
+         --  at compile time, but it is strictly a runtime check, and of
+         --  course there is an ACVC test that checks this.
 
-   -------------------------------------
-   -- Copy_Array_Base_Type_Attributes --
-   -------------------------------------
+         if Digits_Value (Def_Id) > Digits_Value (T) then
+            Error_Msg_Uint_1 := Digits_Value (T);
+            Error_Msg_N ("??digits value is too large, maximum is ^", D);
+            Rais :=
+              Make_Raise_Constraint_Error (Sloc (D),
+                Reason => CE_Range_Check_Failed);
+            Insert_Action (Declaration_Node (Def_Id), Rais);
+         end if;
 
-   procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id) is
-   begin
-      Set_Component_Alignment      (T1, Component_Alignment      (T2));
-      Set_Component_Type           (T1, Component_Type           (T2));
-      Set_Component_Size           (T1, Component_Size           (T2));
-      Set_Has_Controlled_Component (T1, Has_Controlled_Component (T2));
-      Set_Has_Non_Standard_Rep     (T1, Has_Non_Standard_Rep     (T2));
-      Set_Has_Protected            (T1, Has_Protected            (T2));
-      Set_Has_Task                 (T1, Has_Task                 (T2));
-      Set_Is_Packed                (T1, Is_Packed                (T2));
-      Set_Has_Aliased_Components   (T1, Has_Aliased_Components   (T2));
-      Set_Has_Atomic_Components    (T1, Has_Atomic_Components    (T2));
-      Set_Has_Volatile_Components  (T1, Has_Volatile_Components  (T2));
-   end Copy_Array_Base_Type_Attributes;
+         C := Range_Constraint (C);
 
-   -----------------------------------
-   -- Copy_Array_Subtype_Attributes --
-   -----------------------------------
+      --  No digits constraint present
 
-   procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id) is
-   begin
-      Set_Size_Info (T1, T2);
-
-      Set_First_Index          (T1, First_Index           (T2));
-      Set_Is_Aliased           (T1, Is_Aliased            (T2));
-      Set_Is_Volatile          (T1, Is_Volatile           (T2));
-      Set_Treat_As_Volatile    (T1, Treat_As_Volatile     (T2));
-      Set_Is_Constrained       (T1, Is_Constrained        (T2));
-      Set_Depends_On_Private   (T1, Has_Private_Component (T2));
-      Set_First_Rep_Item       (T1, First_Rep_Item        (T2));
-      Set_Convention           (T1, Convention            (T2));
-      Set_Is_Limited_Composite (T1, Is_Limited_Composite  (T2));
-      Set_Is_Private_Composite (T1, Is_Private_Composite  (T2));
-      Set_Packed_Array_Impl_Type    (T1, Packed_Array_Impl_Type     (T2));
-   end Copy_Array_Subtype_Attributes;
+      else
+         Set_Digits_Value (Def_Id, Digits_Value (T));
+      end if;
 
-   -----------------------------------
-   -- Create_Constrained_Components --
-   -----------------------------------
+      --  Range constraint present
 
-   procedure Create_Constrained_Components
-     (Subt        : Entity_Id;
-      Decl_Node   : Node_Id;
-      Typ         : Entity_Id;
-      Constraints : Elist_Id)
-   is
-      Loc         : constant Source_Ptr := Sloc (Subt);
-      Comp_List   : constant Elist_Id   := New_Elmt_List;
-      Parent_Type : constant Entity_Id  := Etype (Typ);
-      Assoc_List  : constant List_Id    := New_List;
-      Discr_Val   : Elmt_Id;
-      Errors      : Boolean;
-      New_C       : Entity_Id;
-      Old_C       : Entity_Id;
-      Is_Static   : Boolean := True;
+      if Nkind (C) = N_Range_Constraint then
+         Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
 
-      procedure Collect_Fixed_Components (Typ : Entity_Id);
-      --  Collect parent type components that do not appear in a variant part
+      --  No range constraint present
 
-      procedure Create_All_Components;
-      --  Iterate over Comp_List to create the components of the subtype
+      else
+         pragma Assert (No (C));
+         Set_Scalar_Range (Def_Id, Scalar_Range (T));
+      end if;
 
-      function Create_Component (Old_Compon : Entity_Id) return Entity_Id;
-      --  Creates a new component from Old_Compon, copying all the fields from
-      --  it, including its Etype, inserts the new component in the Subt entity
-      --  chain and returns the new component.
+      Set_Is_Constrained (Def_Id);
+   end Constrain_Float;
 
-      function Is_Variant_Record (T : Entity_Id) return Boolean;
-      --  If true, and discriminants are static, collect only components from
-      --  variants selected by discriminant values.
+   ---------------------
+   -- Constrain_Index --
+   ---------------------
 
-      ------------------------------
-      -- Collect_Fixed_Components --
-      ------------------------------
+   procedure Constrain_Index
+     (Index        : Node_Id;
+      S            : Node_Id;
+      Related_Nod  : Node_Id;
+      Related_Id   : Entity_Id;
+      Suffix       : Character;
+      Suffix_Index : Nat)
+   is
+      Def_Id : Entity_Id;
+      R      : Node_Id := Empty;
+      T      : constant Entity_Id := Etype (Index);
 
-      procedure Collect_Fixed_Components (Typ : Entity_Id) is
-      begin
-      --  Build association list for discriminants, and find components of the
-      --  variant part selected by the values of the discriminants.
+   begin
+      Def_Id :=
+        Create_Itype (E_Void, Related_Nod, Related_Id, Suffix, Suffix_Index);
+      Set_Etype (Def_Id, Base_Type (T));
 
-         Old_C := First_Discriminant (Typ);
-         Discr_Val := First_Elmt (Constraints);
-         while Present (Old_C) loop
-            Append_To (Assoc_List,
-              Make_Component_Association (Loc,
-                 Choices    => New_List (New_Occurrence_Of (Old_C, Loc)),
-                 Expression => New_Copy (Node (Discr_Val))));
+      if Nkind (S) = N_Range
+        or else
+          (Nkind (S) = N_Attribute_Reference
+            and then Attribute_Name (S) = Name_Range)
+      then
+         --  A Range attribute will be transformed into N_Range by Resolve
 
-            Next_Elmt (Discr_Val);
-            Next_Discriminant (Old_C);
-         end loop;
+         Analyze (S);
+         Set_Etype (S, T);
+         R := S;
 
-         --  The tag and the possible parent component are unconditionally in
-         --  the subtype.
+         Process_Range_Expr_In_Decl (R, T);
 
-         if Is_Tagged_Type (Typ)
-           or else Has_Controlled_Component (Typ)
+         if not Error_Posted (S)
+           and then
+             (Nkind (S) /= N_Range
+               or else not Covers (T, (Etype (Low_Bound (S))))
+               or else not Covers (T, (Etype (High_Bound (S)))))
          then
-            Old_C := First_Component (Typ);
-            while Present (Old_C) loop
-               if Nam_In (Chars (Old_C), Name_uTag, Name_uParent) then
-                  Append_Elmt (Old_C, Comp_List);
-               end if;
-
-               Next_Component (Old_C);
-            end loop;
+            if Base_Type (T) /= Any_Type
+              and then Etype (Low_Bound (S)) /= Any_Type
+              and then Etype (High_Bound (S)) /= Any_Type
+            then
+               Error_Msg_N ("range expected", S);
+            end if;
          end if;
-      end Collect_Fixed_Components;
 
-      ---------------------------
-      -- Create_All_Components --
-      ---------------------------
+      elsif Nkind (S) = N_Subtype_Indication then
 
-      procedure Create_All_Components is
-         Comp : Elmt_Id;
+         --  The parser has verified that this is a discrete indication
 
-      begin
-         Comp := First_Elmt (Comp_List);
-         while Present (Comp) loop
-            Old_C := Node (Comp);
-            New_C := Create_Component (Old_C);
+         Resolve_Discrete_Subtype_Indication (S, T);
+         Bad_Predicated_Subtype_Use
+           ("subtype& has predicate, not allowed in index constraint",
+            S, Entity (Subtype_Mark (S)));
 
-            Set_Etype
-              (New_C,
-               Constrain_Component_Type
-                 (Old_C, Subt, Decl_Node, Typ, Constraints));
-            Set_Is_Public (New_C, Is_Public (Subt));
+         R := Range_Expression (Constraint (S));
 
-            Next_Elmt (Comp);
-         end loop;
-      end Create_All_Components;
+         --  Capture values of bounds and generate temporaries for them if
+         --  needed, since checks may cause duplication of the expressions
+         --  which must not be reevaluated.
 
-      ----------------------
-      -- Create_Component --
-      ----------------------
+         --  The forced evaluation removes side effects from expressions, which
+         --  should occur also in GNATprove mode. Otherwise, we end up with
+         --  unexpected insertions of actions at places where this is not
+         --  supposed to occur, e.g. on default parameters of a call.
 
-      function Create_Component (Old_Compon : Entity_Id) return Entity_Id is
-         New_Compon : constant Entity_Id := New_Copy (Old_Compon);
+         if Expander_Active or GNATprove_Mode then
+            Force_Evaluation
+              (Low_Bound (R),  Related_Id => Def_Id, Is_Low_Bound  => True);
+            Force_Evaluation
+              (High_Bound (R), Related_Id => Def_Id, Is_High_Bound => True);
+         end if;
 
-      begin
-         if Ekind (Old_Compon) = E_Discriminant
-           and then Is_Completely_Hidden (Old_Compon)
-         then
-            --  This is a shadow discriminant created for a discriminant of
-            --  the parent type, which needs to be present in the subtype.
-            --  Give the shadow discriminant an internal name that cannot
-            --  conflict with that of visible components.
+      elsif Nkind (S) = N_Discriminant_Association then
 
-            Set_Chars (New_Compon, New_Internal_Name ('C'));
-         end if;
+         --  Syntactically valid in subtype indication
 
-         --  Set the parent so we have a proper link for freezing etc. This is
-         --  not a real parent pointer, since of course our parent does not own
-         --  up to us and reference us, we are an illegitimate child of the
-         --  original parent.
+         Error_Msg_N ("invalid index constraint", S);
+         Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
+         return;
 
-         Set_Parent (New_Compon, Parent (Old_Compon));
+      --  Subtype_Mark case, no anonymous subtypes to construct
 
-         --  If the old component's Esize was already determined and is a
-         --  static value, then the new component simply inherits it. Otherwise
-         --  the old component's size may require run-time determination, but
-         --  the new component's size still might be statically determinable
-         --  (if, for example it has a static constraint). In that case we want
-         --  Layout_Type to recompute the component's size, so we reset its
-         --  size and positional fields.
+      else
+         Analyze (S);
 
-         if Frontend_Layout_On_Target
-           and then not Known_Static_Esize (Old_Compon)
-         then
-            Set_Esize (New_Compon, Uint_0);
-            Init_Normalized_First_Bit    (New_Compon);
-            Init_Normalized_Position     (New_Compon);
-            Init_Normalized_Position_Max (New_Compon);
-         end if;
+         if Is_Entity_Name (S) then
+            if not Is_Type (Entity (S)) then
+               Error_Msg_N ("expect subtype mark for index constraint", S);
 
-         --  We do not want this node marked as Comes_From_Source, since
-         --  otherwise it would get first class status and a separate cross-
-         --  reference line would be generated. Illegitimate children do not
-         --  rate such recognition.
+            elsif Base_Type (Entity (S)) /= Base_Type (T) then
+               Wrong_Type (S, Base_Type (T));
 
-         Set_Comes_From_Source (New_Compon, False);
+            --  Check error of subtype with predicate in index constraint
 
-         --  But it is a real entity, and a birth certificate must be properly
-         --  registered by entering it into the entity list.
+            else
+               Bad_Predicated_Subtype_Use
+                 ("subtype& has predicate, not allowed in index constraint",
+                  S, Entity (S));
+            end if;
 
-         Enter_Name (New_Compon);
+            return;
 
-         return New_Compon;
-      end Create_Component;
+         else
+            Error_Msg_N ("invalid index constraint", S);
+            Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
+            return;
+         end if;
+      end if;
 
-      -----------------------
-      -- Is_Variant_Record --
-      -----------------------
+      --  Complete construction of the Itype
 
-      function Is_Variant_Record (T : Entity_Id) return Boolean is
-      begin
-         return Nkind (Parent (T)) = N_Full_Type_Declaration
-           and then Nkind (Type_Definition (Parent (T))) = N_Record_Definition
-           and then Present (Component_List (Type_Definition (Parent (T))))
-           and then
-             Present
-               (Variant_Part (Component_List (Type_Definition (Parent (T)))));
-      end Is_Variant_Record;
+      if Is_Modular_Integer_Type (T) then
+         Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
 
-   --  Start of processing for Create_Constrained_Components
+      elsif Is_Integer_Type (T) then
+         Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
 
-   begin
-      pragma Assert (Subt /= Base_Type (Subt));
-      pragma Assert (Typ = Base_Type (Typ));
+      else
+         Set_Ekind (Def_Id, E_Enumeration_Subtype);
+         Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
+         Set_First_Literal     (Def_Id, First_Literal (T));
+      end if;
 
-      Set_First_Entity (Subt, Empty);
-      Set_Last_Entity  (Subt, Empty);
+      Set_Size_Info      (Def_Id,                (T));
+      Set_RM_Size        (Def_Id, RM_Size        (T));
+      Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
 
-      --  Check whether constraint is fully static, in which case we can
-      --  optimize the list of components.
+      Set_Scalar_Range   (Def_Id, R);
 
-      Discr_Val := First_Elmt (Constraints);
-      while Present (Discr_Val) loop
-         if not Is_OK_Static_Expression (Node (Discr_Val)) then
-            Is_Static := False;
-            exit;
-         end if;
-
-         Next_Elmt (Discr_Val);
-      end loop;
-
-      Set_Has_Static_Discriminants (Subt, Is_Static);
-
-      Push_Scope (Subt);
+      Set_Etype (S, Def_Id);
+      Set_Discrete_RM_Size (Def_Id);
+   end Constrain_Index;
 
-      --  Inherit the discriminants of the parent type
+   -----------------------
+   -- Constrain_Integer --
+   -----------------------
 
-      Add_Discriminants : declare
-         Num_Disc : Int;
-         Num_Gird : Int;
+   procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id) is
+      T : constant Entity_Id := Entity (Subtype_Mark (S));
+      C : constant Node_Id   := Constraint (S);
 
-      begin
-         Num_Disc := 0;
-         Old_C := First_Discriminant (Typ);
+   begin
+      Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
 
-         while Present (Old_C) loop
-            Num_Disc := Num_Disc + 1;
-            New_C := Create_Component (Old_C);
-            Set_Is_Public (New_C, Is_Public (Subt));
-            Next_Discriminant (Old_C);
-         end loop;
+      if Is_Modular_Integer_Type (T) then
+         Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
+      else
+         Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
+      end if;
 
-         --  For an untagged derived subtype, the number of discriminants may
-         --  be smaller than the number of inherited discriminants, because
-         --  several of them may be renamed by a single new discriminant or
-         --  constrained. In this case, add the hidden discriminants back into
-         --  the subtype, because they need to be present if the optimizer of
-         --  the GCC 4.x back-end decides to break apart assignments between
-         --  objects using the parent view into member-wise assignments.
+      Set_Etype            (Def_Id, Base_Type      (T));
+      Set_Size_Info        (Def_Id,                (T));
+      Set_First_Rep_Item   (Def_Id, First_Rep_Item (T));
+      Set_Discrete_RM_Size (Def_Id);
+   end Constrain_Integer;
 
-         Num_Gird := 0;
+   ------------------------------
+   -- Constrain_Ordinary_Fixed --
+   ------------------------------
 
-         if Is_Derived_Type (Typ)
-           and then not Is_Tagged_Type (Typ)
-         then
-            Old_C := First_Stored_Discriminant (Typ);
+   procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id) is
+      T    : constant Entity_Id := Entity (Subtype_Mark (S));
+      C    : Node_Id;
+      D    : Node_Id;
+      Rais : Node_Id;
 
-            while Present (Old_C) loop
-               Num_Gird := Num_Gird + 1;
-               Next_Stored_Discriminant (Old_C);
-            end loop;
-         end if;
+   begin
+      Set_Ekind          (Def_Id, E_Ordinary_Fixed_Point_Subtype);
+      Set_Etype          (Def_Id, Base_Type      (T));
+      Set_Size_Info      (Def_Id,                (T));
+      Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
+      Set_Small_Value    (Def_Id, Small_Value    (T));
 
-         if Num_Gird > Num_Disc then
+      --  Process the constraint
 
-            --  Find out multiple uses of new discriminants, and add hidden
-            --  components for the extra renamed discriminants. We recognize
-            --  multiple uses through the Corresponding_Discriminant of a
-            --  new discriminant: if it constrains several old discriminants,
-            --  this field points to the last one in the parent type. The
-            --  stored discriminants of the derived type have the same name
-            --  as those of the parent.
+      C := Constraint (S);
 
-            declare
-               Constr    : Elmt_Id;
-               New_Discr : Entity_Id;
-               Old_Discr : Entity_Id;
+      --  Delta constraint present
 
-            begin
-               Constr    := First_Elmt (Stored_Constraint (Typ));
-               Old_Discr := First_Stored_Discriminant (Typ);
-               while Present (Constr) loop
-                  if Is_Entity_Name (Node (Constr))
-                    and then Ekind (Entity (Node (Constr))) = E_Discriminant
-                  then
-                     New_Discr := Entity (Node (Constr));
+      if Nkind (C) = N_Delta_Constraint then
 
-                     if Chars (Corresponding_Discriminant (New_Discr)) /=
-                        Chars (Old_Discr)
-                     then
-                        --  The new discriminant has been used to rename a
-                        --  subsequent old discriminant. Introduce a shadow
-                        --  component for the current old discriminant.
+         Check_SPARK_05_Restriction ("delta constraint is not allowed", S);
+         Check_Restriction (No_Obsolescent_Features, C);
 
-                        New_C := Create_Component (Old_Discr);
-                        Set_Original_Record_Component (New_C, Old_Discr);
-                     end if;
+         if Warn_On_Obsolescent_Feature then
+            Error_Msg_S
+              ("subtype delta constraint is an " &
+               "obsolescent feature (RM J.3(7))?j?");
+         end if;
 
-                  else
-                     --  The constraint has eliminated the old discriminant.
-                     --  Introduce a shadow component.
+         D := Delta_Expression (C);
+         Analyze_And_Resolve (D, Any_Real);
+         Check_Delta_Expression (D);
+         Set_Delta_Value (Def_Id, Expr_Value_R (D));
 
-                     New_C := Create_Component (Old_Discr);
-                     Set_Original_Record_Component (New_C, Old_Discr);
-                  end if;
+         --  Check that delta value is in range. Obviously we can do this
+         --  at compile time, but it is strictly a runtime check, and of
+         --  course there is an ACVC test that checks this.
 
-                  Next_Elmt (Constr);
-                  Next_Stored_Discriminant (Old_Discr);
-               end loop;
-            end;
+         if Delta_Value (Def_Id) < Delta_Value (T) then
+            Error_Msg_N ("??delta value is too small", D);
+            Rais :=
+              Make_Raise_Constraint_Error (Sloc (D),
+                Reason => CE_Range_Check_Failed);
+            Insert_Action (Declaration_Node (Def_Id), Rais);
          end if;
-      end Add_Discriminants;
 
-      if Is_Static
-        and then Is_Variant_Record (Typ)
-      then
-         Collect_Fixed_Components (Typ);
+         C := Range_Constraint (C);
 
-         Gather_Components (
-           Typ,
-           Component_List (Type_Definition (Parent (Typ))),
-           Governed_By   => Assoc_List,
-           Into          => Comp_List,
-           Report_Errors => Errors);
-         pragma Assert (not Errors);
+      --  No delta constraint present
 
-         Create_All_Components;
+      else
+         Set_Delta_Value (Def_Id, Delta_Value (T));
+      end if;
 
-      --  If the subtype declaration is created for a tagged type derivation
-      --  with constraints, we retrieve the record definition of the parent
-      --  type to select the components of the proper variant.
+      --  Range constraint present
 
-      elsif Is_Static
-        and then Is_Tagged_Type (Typ)
-        and then Nkind (Parent (Typ)) = N_Full_Type_Declaration
-        and then
-          Nkind (Type_Definition (Parent (Typ))) = N_Derived_Type_Definition
-        and then Is_Variant_Record (Parent_Type)
-      then
-         Collect_Fixed_Components (Typ);
+      if Nkind (C) = N_Range_Constraint then
+         Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
 
-         Gather_Components (
-           Typ,
-           Component_List (Type_Definition (Parent (Parent_Type))),
-           Governed_By   => Assoc_List,
-           Into          => Comp_List,
-           Report_Errors => Errors);
-         pragma Assert (not Errors);
+      --  No range constraint present
 
-         --  If the tagged derivation has a type extension, collect all the
-         --  new components therein.
+      else
+         pragma Assert (No (C));
+         Set_Scalar_Range (Def_Id, Scalar_Range (T));
+      end if;
 
-         if Present
-              (Record_Extension_Part (Type_Definition (Parent (Typ))))
-         then
-            Old_C := First_Component (Typ);
-            while Present (Old_C) loop
-               if Original_Record_Component (Old_C) = Old_C
-                 and then Chars (Old_C) /= Name_uTag
-                 and then Chars (Old_C) /= Name_uParent
-               then
-                  Append_Elmt (Old_C, Comp_List);
-               end if;
+      Set_Discrete_RM_Size (Def_Id);
 
-               Next_Component (Old_C);
-            end loop;
-         end if;
+      --  Unconditionally delay the freeze, since we cannot set size
+      --  information in all cases correctly until the freeze point.
 
-         Create_All_Components;
+      Set_Has_Delayed_Freeze (Def_Id);
+   end Constrain_Ordinary_Fixed;
 
-      else
-         --  If discriminants are not static, or if this is a multi-level type
-         --  extension, we have to include all components of the parent type.
+   -----------------------
+   -- Contain_Interface --
+   -----------------------
 
-         Old_C := First_Component (Typ);
-         while Present (Old_C) loop
-            New_C := Create_Component (Old_C);
+   function Contain_Interface
+     (Iface  : Entity_Id;
+      Ifaces : Elist_Id) return Boolean
+   is
+      Iface_Elmt : Elmt_Id;
 
-            Set_Etype
-              (New_C,
-               Constrain_Component_Type
-                 (Old_C, Subt, Decl_Node, Typ, Constraints));
-            Set_Is_Public (New_C, Is_Public (Subt));
+   begin
+      if Present (Ifaces) then
+         Iface_Elmt := First_Elmt (Ifaces);
+         while Present (Iface_Elmt) loop
+            if Node (Iface_Elmt) = Iface then
+               return True;
+            end if;
 
-            Next_Component (Old_C);
+            Next_Elmt (Iface_Elmt);
          end loop;
       end if;
 
-      End_Scope;
-   end Create_Constrained_Components;
+      return False;
+   end Contain_Interface;
 
-   ------------------------------------------
-   -- Decimal_Fixed_Point_Type_Declaration --
-   ------------------------------------------
+   ---------------------------
+   -- Convert_Scalar_Bounds --
+   ---------------------------
 
-   procedure Decimal_Fixed_Point_Type_Declaration
-     (T   : Entity_Id;
-      Def : Node_Id)
+   procedure Convert_Scalar_Bounds
+     (N            : Node_Id;
+      Parent_Type  : Entity_Id;
+      Derived_Type : Entity_Id;
+      Loc          : Source_Ptr)
    is
-      Loc           : constant Source_Ptr := Sloc (Def);
-      Digs_Expr     : constant Node_Id    := Digits_Expression (Def);
-      Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
-      Implicit_Base : Entity_Id;
-      Digs_Val      : Uint;
-      Delta_Val     : Ureal;
-      Scale_Val     : Uint;
-      Bound_Val     : Ureal;
+      Implicit_Base : constant Entity_Id := Base_Type (Derived_Type);
 
-   begin
-      Check_SPARK_Restriction
-        ("decimal fixed point type is not allowed", Def);
-      Check_Restriction (No_Fixed_Point, Def);
-
-      --  Create implicit base type
+      Lo  : Node_Id;
+      Hi  : Node_Id;
+      Rng : Node_Id;
 
-      Implicit_Base :=
-        Create_Itype (E_Decimal_Fixed_Point_Type, Parent (Def), T, 'B');
-      Set_Etype (Implicit_Base, Implicit_Base);
+   begin
+      --  Defend against previous errors
 
-      --  Analyze and process delta expression
+      if No (Scalar_Range (Derived_Type)) then
+         Check_Error_Detected;
+         return;
+      end if;
 
-      Analyze_And_Resolve (Delta_Expr, Universal_Real);
+      Lo := Build_Scalar_Bound
+              (Type_Low_Bound (Derived_Type),
+               Parent_Type, Implicit_Base);
 
-      Check_Delta_Expression (Delta_Expr);
-      Delta_Val := Expr_Value_R (Delta_Expr);
+      Hi := Build_Scalar_Bound
+              (Type_High_Bound (Derived_Type),
+               Parent_Type, Implicit_Base);
 
-      --  Check delta is power of 10, and determine scale value from it
+      Rng :=
+        Make_Range (Loc,
+          Low_Bound  => Lo,
+          High_Bound => Hi);
 
-      declare
-         Val : Ureal;
+      Set_Includes_Infinities (Rng, Has_Infinities (Derived_Type));
 
-      begin
-         Scale_Val := Uint_0;
-         Val := Delta_Val;
+      Set_Parent (Rng, N);
+      Set_Scalar_Range (Derived_Type, Rng);
 
-         if Val < Ureal_1 then
-            while Val < Ureal_1 loop
-               Val := Val * Ureal_10;
-               Scale_Val := Scale_Val + 1;
-            end loop;
+      --  Analyze the bounds
 
-            if Scale_Val > 18 then
-               Error_Msg_N ("scale exceeds maximum value of 18", Def);
-               Scale_Val := UI_From_Int (+18);
-            end if;
+      Analyze_And_Resolve (Lo, Implicit_Base);
+      Analyze_And_Resolve (Hi, Implicit_Base);
 
-         else
-            while Val > Ureal_1 loop
-               Val := Val / Ureal_10;
-               Scale_Val := Scale_Val - 1;
-            end loop;
+      --  Analyze the range itself, except that we do not analyze it if
+      --  the bounds are real literals, and we have a fixed-point type.
+      --  The reason for this is that we delay setting the bounds in this
+      --  case till we know the final Small and Size values (see circuit
+      --  in Freeze.Freeze_Fixed_Point_Type for further details).
 
-            if Scale_Val < -18 then
-               Error_Msg_N ("scale is less than minimum value of -18", Def);
-               Scale_Val := UI_From_Int (-18);
-            end if;
-         end if;
+      if Is_Fixed_Point_Type (Parent_Type)
+        and then Nkind (Lo) = N_Real_Literal
+        and then Nkind (Hi) = N_Real_Literal
+      then
+         return;
 
-         if Val /= Ureal_1 then
-            Error_Msg_N ("delta expression must be a power of 10", Def);
-            Delta_Val := Ureal_10 ** (-Scale_Val);
-         end if;
-      end;
+      --  Here we do the analysis of the range
 
-      --  Set delta, scale and small (small = delta for decimal type)
+      --  Note: we do this manually, since if we do a normal Analyze and
+      --  Resolve call, there are problems with the conversions used for
+      --  the derived type range.
 
-      Set_Delta_Value (Implicit_Base, Delta_Val);
-      Set_Scale_Value (Implicit_Base, Scale_Val);
-      Set_Small_Value (Implicit_Base, Delta_Val);
+      else
+         Set_Etype    (Rng, Implicit_Base);
+         Set_Analyzed (Rng, True);
+      end if;
+   end Convert_Scalar_Bounds;
 
-      --  Analyze and process digits expression
+   -------------------
+   -- Copy_And_Swap --
+   -------------------
 
-      Analyze_And_Resolve (Digs_Expr, Any_Integer);
-      Check_Digits_Expression (Digs_Expr);
-      Digs_Val := Expr_Value (Digs_Expr);
+   procedure Copy_And_Swap (Priv, Full : Entity_Id) is
+   begin
+      --  Initialize new full declaration entity by copying the pertinent
+      --  fields of the corresponding private declaration entity.
 
-      if Digs_Val > 18 then
-         Digs_Val := UI_From_Int (+18);
-         Error_Msg_N ("digits value out of range, maximum is 18", Digs_Expr);
-      end if;
+      --  We temporarily set Ekind to a value appropriate for a type to
+      --  avoid assert failures in Einfo from checking for setting type
+      --  attributes on something that is not a type. Ekind (Priv) is an
+      --  appropriate choice, since it allowed the attributes to be set
+      --  in the first place. This Ekind value will be modified later.
 
-      Set_Digits_Value (Implicit_Base, Digs_Val);
-      Bound_Val := UR_From_Uint (10 ** Digs_Val - 1) * Delta_Val;
+      Set_Ekind (Full, Ekind (Priv));
 
-      --  Set range of base type from digits value for now. This will be
-      --  expanded to represent the true underlying base range by Freeze.
+      --  Also set Etype temporarily to Any_Type, again, in the absence
+      --  of errors, it will be properly reset, and if there are errors,
+      --  then we want a value of Any_Type to remain.
 
-      Set_Fixed_Range (Implicit_Base, Loc, -Bound_Val, Bound_Val);
+      Set_Etype (Full, Any_Type);
 
-      --  Note: We leave size as zero for now, size will be set at freeze
-      --  time. We have to do this for ordinary fixed-point, because the size
-      --  depends on the specified small, and we might as well do the same for
-      --  decimal fixed-point.
+      --  Now start copying attributes
 
-      pragma Assert (Esize (Implicit_Base) = Uint_0);
+      Set_Has_Discriminants          (Full, Has_Discriminants       (Priv));
 
-      --  If there are bounds given in the declaration use them as the
-      --  bounds of the first named subtype.
+      if Has_Discriminants (Full) then
+         Set_Discriminant_Constraint (Full, Discriminant_Constraint (Priv));
+         Set_Stored_Constraint       (Full, Stored_Constraint       (Priv));
+      end if;
 
-      if Present (Real_Range_Specification (Def)) then
-         declare
-            RRS      : constant Node_Id := Real_Range_Specification (Def);
-            Low      : constant Node_Id := Low_Bound (RRS);
-            High     : constant Node_Id := High_Bound (RRS);
-            Low_Val  : Ureal;
-            High_Val : Ureal;
+      Set_First_Rep_Item             (Full, First_Rep_Item          (Priv));
+      Set_Homonym                    (Full, Homonym                 (Priv));
+      Set_Is_Immediately_Visible     (Full, Is_Immediately_Visible  (Priv));
+      Set_Is_Public                  (Full, Is_Public               (Priv));
+      Set_Is_Pure                    (Full, Is_Pure                 (Priv));
+      Set_Is_Tagged_Type             (Full, Is_Tagged_Type          (Priv));
+      Set_Has_Pragma_Unmodified      (Full, Has_Pragma_Unmodified   (Priv));
+      Set_Has_Pragma_Unreferenced    (Full, Has_Pragma_Unreferenced (Priv));
+      Set_Has_Pragma_Unreferenced_Objects
+                                     (Full, Has_Pragma_Unreferenced_Objects
+                                                                    (Priv));
 
-         begin
-            Analyze_And_Resolve (Low, Any_Real);
-            Analyze_And_Resolve (High, Any_Real);
-            Check_Real_Bound (Low);
-            Check_Real_Bound (High);
-            Low_Val := Expr_Value_R (Low);
-            High_Val := Expr_Value_R (High);
+      Conditional_Delay              (Full,                          Priv);
 
-            if Low_Val < (-Bound_Val) then
-               Error_Msg_N
-                 ("range low bound too small for digits value", Low);
-               Low_Val := -Bound_Val;
-            end if;
+      if Is_Tagged_Type (Full) then
+         Set_Direct_Primitive_Operations
+           (Full, Direct_Primitive_Operations (Priv));
+         Set_No_Tagged_Streams_Pragma
+           (Full, No_Tagged_Streams_Pragma (Priv));
 
-            if High_Val > Bound_Val then
-               Error_Msg_N
-                 ("range high bound too large for digits value", High);
-               High_Val := Bound_Val;
-            end if;
+         if Is_Base_Type (Priv) then
+            Set_Class_Wide_Type      (Full, Class_Wide_Type         (Priv));
+         end if;
+      end if;
 
-            Set_Fixed_Range (T, Loc, Low_Val, High_Val);
-         end;
+      Set_Is_Volatile                (Full, Is_Volatile             (Priv));
+      Set_Treat_As_Volatile          (Full, Treat_As_Volatile       (Priv));
+      Set_Scope                      (Full, Scope                   (Priv));
+      Set_Next_Entity                (Full, Next_Entity             (Priv));
+      Set_First_Entity               (Full, First_Entity            (Priv));
+      Set_Last_Entity                (Full, Last_Entity             (Priv));
 
-      --  If no explicit range, use range that corresponds to given
-      --  digits value. This will end up as the final range for the
-      --  first subtype.
+      --  If access types have been recorded for later handling, keep them in
+      --  the full view so that they get handled when the full view freeze
+      --  node is expanded.
 
-      else
-         Set_Fixed_Range (T, Loc, -Bound_Val, Bound_Val);
+      if Present (Freeze_Node (Priv))
+        and then Present (Access_Types_To_Process (Freeze_Node (Priv)))
+      then
+         Ensure_Freeze_Node (Full);
+         Set_Access_Types_To_Process
+           (Freeze_Node (Full),
+            Access_Types_To_Process (Freeze_Node (Priv)));
       end if;
 
-      --  Complete entity for first subtype
+      --  Swap the two entities. Now Private is the full type entity and Full
+      --  is the private one. They will be swapped back at the end of the
+      --  private part. This swapping ensures that the entity that is visible
+      --  in the private part is the full declaration.
 
-      Set_Ekind          (T, E_Decimal_Fixed_Point_Subtype);
-      Set_Etype          (T, Implicit_Base);
-      Set_Size_Info      (T, Implicit_Base);
-      Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
-      Set_Digits_Value   (T, Digs_Val);
-      Set_Delta_Value    (T, Delta_Val);
-      Set_Small_Value    (T, Delta_Val);
-      Set_Scale_Value    (T, Scale_Val);
-      Set_Is_Constrained (T);
-   end Decimal_Fixed_Point_Type_Declaration;
+      Exchange_Entities (Priv, Full);
+      Append_Entity (Full, Scope (Full));
+   end Copy_And_Swap;
+
+   -------------------------------------
+   -- Copy_Array_Base_Type_Attributes --
+   -------------------------------------
+
+   procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id) is
+   begin
+      Set_Component_Alignment      (T1, Component_Alignment      (T2));
+      Set_Component_Type           (T1, Component_Type           (T2));
+      Set_Component_Size           (T1, Component_Size           (T2));
+      Set_Has_Controlled_Component (T1, Has_Controlled_Component (T2));
+      Set_Has_Non_Standard_Rep     (T1, Has_Non_Standard_Rep     (T2));
+      Set_Has_Protected            (T1, Has_Protected            (T2));
+      Set_Has_Task                 (T1, Has_Task                 (T2));
+      Set_Is_Packed                (T1, Is_Packed                (T2));
+      Set_Has_Aliased_Components   (T1, Has_Aliased_Components   (T2));
+      Set_Has_Atomic_Components    (T1, Has_Atomic_Components    (T2));
+      Set_Has_Volatile_Components  (T1, Has_Volatile_Components  (T2));
+   end Copy_Array_Base_Type_Attributes;
 
    -----------------------------------
-   -- Derive_Progenitor_Subprograms --
+   -- Copy_Array_Subtype_Attributes --
    -----------------------------------
 
-   procedure Derive_Progenitor_Subprograms
-     (Parent_Type : Entity_Id;
-      Tagged_Type : Entity_Id)
-   is
-      E          : Entity_Id;
-      Elmt       : Elmt_Id;
-      Iface      : Entity_Id;
-      Iface_Elmt : Elmt_Id;
-      Iface_Subp : Entity_Id;
-      New_Subp   : Entity_Id := Empty;
-      Prim_Elmt  : Elmt_Id;
-      Subp       : Entity_Id;
-      Typ        : Entity_Id;
-
+   procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id) is
    begin
-      pragma Assert (Ada_Version >= Ada_2005
-        and then Is_Record_Type (Tagged_Type)
-        and then Is_Tagged_Type (Tagged_Type)
-        and then Has_Interfaces (Tagged_Type));
+      Set_Size_Info (T1, T2);
 
-      --  Step 1: Transfer to the full-view primitives associated with the
-      --  partial-view that cover interface primitives. Conceptually this
-      --  work should be done later by Process_Full_View; done here to
-      --  simplify its implementation at later stages. It can be safely
-      --  done here because interfaces must be visible in the partial and
-      --  private view (RM 7.3(7.3/2)).
+      Set_First_Index            (T1, First_Index            (T2));
+      Set_Is_Aliased             (T1, Is_Aliased             (T2));
+      Set_Is_Volatile            (T1, Is_Volatile            (T2));
+      Set_Treat_As_Volatile      (T1, Treat_As_Volatile      (T2));
+      Set_Is_Constrained         (T1, Is_Constrained         (T2));
+      Set_Depends_On_Private     (T1, Has_Private_Component  (T2));
+      Inherit_Rep_Item_Chain     (T1,                         T2);
+      Set_Convention             (T1, Convention             (T2));
+      Set_Is_Limited_Composite   (T1, Is_Limited_Composite   (T2));
+      Set_Is_Private_Composite   (T1, Is_Private_Composite   (T2));
+      Set_Packed_Array_Impl_Type (T1, Packed_Array_Impl_Type (T2));
+   end Copy_Array_Subtype_Attributes;
 
-      --  Small optimization: This work is only required if the parent may
-      --  have entities whose Alias attribute reference an interface primitive.
-      --  Such a situation may occur if the parent is an abstract type and the
-      --  primitive has not been yet overridden or if the parent is a generic
-      --  formal type covering interfaces.
+   -----------------------------------
+   -- Create_Constrained_Components --
+   -----------------------------------
 
-      --  If the tagged type is not abstract, it cannot have abstract
-      --  primitives (the only entities in the list of primitives of
-      --  non-abstract tagged types that can reference abstract primitives
-      --  through its Alias attribute are the internal entities that have
-      --  attribute Interface_Alias, and these entities are generated later
-      --  by Add_Internal_Interface_Entities).
+   procedure Create_Constrained_Components
+     (Subt        : Entity_Id;
+      Decl_Node   : Node_Id;
+      Typ         : Entity_Id;
+      Constraints : Elist_Id)
+   is
+      Loc         : constant Source_Ptr := Sloc (Subt);
+      Comp_List   : constant Elist_Id   := New_Elmt_List;
+      Parent_Type : constant Entity_Id  := Etype (Typ);
+      Assoc_List  : constant List_Id    := New_List;
+      Discr_Val   : Elmt_Id;
+      Errors      : Boolean;
+      New_C       : Entity_Id;
+      Old_C       : Entity_Id;
+      Is_Static   : Boolean := True;
 
-      if In_Private_Part (Current_Scope)
-        and then (Is_Abstract_Type (Parent_Type)
-                    or else
-                  Is_Generic_Type  (Parent_Type))
-      then
-         Elmt := First_Elmt (Primitive_Operations (Tagged_Type));
-         while Present (Elmt) loop
-            Subp := Node (Elmt);
+      procedure Collect_Fixed_Components (Typ : Entity_Id);
+      --  Collect parent type components that do not appear in a variant part
 
-            --  At this stage it is not possible to have entities in the list
-            --  of primitives that have attribute Interface_Alias.
+      procedure Create_All_Components;
+      --  Iterate over Comp_List to create the components of the subtype
 
-            pragma Assert (No (Interface_Alias (Subp)));
+      function Create_Component (Old_Compon : Entity_Id) return Entity_Id;
+      --  Creates a new component from Old_Compon, copying all the fields from
+      --  it, including its Etype, inserts the new component in the Subt entity
+      --  chain and returns the new component.
 
-            Typ := Find_Dispatching_Type (Ultimate_Alias (Subp));
+      function Is_Variant_Record (T : Entity_Id) return Boolean;
+      --  If true, and discriminants are static, collect only components from
+      --  variants selected by discriminant values.
 
-            if Is_Interface (Typ) then
-               E := Find_Primitive_Covering_Interface
-                      (Tagged_Type => Tagged_Type,
-                       Iface_Prim  => Subp);
+      ------------------------------
+      -- Collect_Fixed_Components --
+      ------------------------------
 
-               if Present (E)
-                 and then Find_Dispatching_Type (Ultimate_Alias (E)) /= Typ
-               then
-                  Replace_Elmt (Elmt, E);
-                  Remove_Homonym (Subp);
-               end if;
-            end if;
+      procedure Collect_Fixed_Components (Typ : Entity_Id) is
+      begin
+      --  Build association list for discriminants, and find components of the
+      --  variant part selected by the values of the discriminants.
 
-            Next_Elmt (Elmt);
-         end loop;
-      end if;
+         Old_C := First_Discriminant (Typ);
+         Discr_Val := First_Elmt (Constraints);
+         while Present (Old_C) loop
+            Append_To (Assoc_List,
+              Make_Component_Association (Loc,
+                 Choices    => New_List (New_Occurrence_Of (Old_C, Loc)),
+                 Expression => New_Copy (Node (Discr_Val))));
 
-      --  Step 2: Add primitives of progenitors that are not implemented by
-      --  parents of Tagged_Type.
+            Next_Elmt (Discr_Val);
+            Next_Discriminant (Old_C);
+         end loop;
 
-      if Present (Interfaces (Base_Type (Tagged_Type))) then
-         Iface_Elmt := First_Elmt (Interfaces (Base_Type (Tagged_Type)));
-         while Present (Iface_Elmt) loop
-            Iface := Node (Iface_Elmt);
+         --  The tag and the possible parent component are unconditionally in
+         --  the subtype.
 
-            Prim_Elmt := First_Elmt (Primitive_Operations (Iface));
-            while Present (Prim_Elmt) loop
-               Iface_Subp := Node (Prim_Elmt);
+         if Is_Tagged_Type (Typ) or else Has_Controlled_Component (Typ) then
+            Old_C := First_Component (Typ);
+            while Present (Old_C) loop
+               if Nam_In (Chars (Old_C), Name_uTag, Name_uParent) then
+                  Append_Elmt (Old_C, Comp_List);
+               end if;
 
-               --  Exclude derivation of predefined primitives except those
-               --  that come from source, or are inherited from one that comes
-               --  from source. Required to catch declarations of equality
-               --  operators of interfaces. For example:
+               Next_Component (Old_C);
+            end loop;
+         end if;
+      end Collect_Fixed_Components;
 
-               --     type Iface is interface;
-               --     function "=" (Left, Right : Iface) return Boolean;
+      ---------------------------
+      -- Create_All_Components --
+      ---------------------------
 
-               if not Is_Predefined_Dispatching_Operation (Iface_Subp)
-                 or else Comes_From_Source (Ultimate_Alias (Iface_Subp))
-               then
-                  E := Find_Primitive_Covering_Interface
-                         (Tagged_Type => Tagged_Type,
-                          Iface_Prim  => Iface_Subp);
+      procedure Create_All_Components is
+         Comp : Elmt_Id;
 
-                  --  If not found we derive a new primitive leaving its alias
-                  --  attribute referencing the interface primitive.
+      begin
+         Comp := First_Elmt (Comp_List);
+         while Present (Comp) loop
+            Old_C := Node (Comp);
+            New_C := Create_Component (Old_C);
 
-                  if No (E) then
-                     Derive_Subprogram
-                       (New_Subp, Iface_Subp, Tagged_Type, Iface);
+            Set_Etype
+              (New_C,
+               Constrain_Component_Type
+                 (Old_C, Subt, Decl_Node, Typ, Constraints));
+            Set_Is_Public (New_C, Is_Public (Subt));
 
-                  --  Ada 2012 (AI05-0197): If the covering primitive's name
-                  --  differs from the name of the interface primitive then it
-                  --  is a private primitive inherited from a parent type. In
-                  --  such case, given that Tagged_Type covers the interface,
-                  --  the inherited private primitive becomes visible. For such
-                  --  purpose we add a new entity that renames the inherited
-                  --  private primitive.
+            Next_Elmt (Comp);
+         end loop;
+      end Create_All_Components;
 
-                  elsif Chars (E) /= Chars (Iface_Subp) then
-                     pragma Assert (Has_Suffix (E, 'P'));
-                     Derive_Subprogram
-                       (New_Subp, Iface_Subp, Tagged_Type, Iface);
-                     Set_Alias (New_Subp, E);
-                     Set_Is_Abstract_Subprogram (New_Subp,
-                       Is_Abstract_Subprogram (E));
+      ----------------------
+      -- Create_Component --
+      ----------------------
 
-                  --  Propagate to the full view interface entities associated
-                  --  with the partial view.
+      function Create_Component (Old_Compon : Entity_Id) return Entity_Id is
+         New_Compon : constant Entity_Id := New_Copy (Old_Compon);
 
-                  elsif In_Private_Part (Current_Scope)
-                    and then Present (Alias (E))
-                    and then Alias (E) = Iface_Subp
-                    and then
-                      List_Containing (Parent (E)) /=
-                        Private_Declarations
-                          (Specification
-                            (Unit_Declaration_Node (Current_Scope)))
-                  then
-                     Append_Elmt (E, Primitive_Operations (Tagged_Type));
-                  end if;
-               end if;
+      begin
+         if Ekind (Old_Compon) = E_Discriminant
+           and then Is_Completely_Hidden (Old_Compon)
+         then
+            --  This is a shadow discriminant created for a discriminant of
+            --  the parent type, which needs to be present in the subtype.
+            --  Give the shadow discriminant an internal name that cannot
+            --  conflict with that of visible components.
 
-               Next_Elmt (Prim_Elmt);
-            end loop;
+            Set_Chars (New_Compon, New_Internal_Name ('C'));
+         end if;
 
-            Next_Elmt (Iface_Elmt);
-         end loop;
-      end if;
-   end Derive_Progenitor_Subprograms;
+         --  Set the parent so we have a proper link for freezing etc. This is
+         --  not a real parent pointer, since of course our parent does not own
+         --  up to us and reference us, we are an illegitimate child of the
+         --  original parent.
 
-   -----------------------
-   -- Derive_Subprogram --
-   -----------------------
+         Set_Parent (New_Compon, Parent (Old_Compon));
 
-   procedure Derive_Subprogram
-     (New_Subp     : in out Entity_Id;
-      Parent_Subp  : Entity_Id;
-      Derived_Type : Entity_Id;
-      Parent_Type  : Entity_Id;
-      Actual_Subp  : Entity_Id := Empty)
-   is
-      Formal : Entity_Id;
-      --  Formal parameter of parent primitive operation
+         --  If the old component's Esize was already determined and is a
+         --  static value, then the new component simply inherits it. Otherwise
+         --  the old component's size may require run-time determination, but
+         --  the new component's size still might be statically determinable
+         --  (if, for example it has a static constraint). In that case we want
+         --  Layout_Type to recompute the component's size, so we reset its
+         --  size and positional fields.
 
-      Formal_Of_Actual : Entity_Id;
-      --  Formal parameter of actual operation, when the derivation is to
-      --  create a renaming for a primitive operation of an actual in an
-      --  instantiation.
+         if Frontend_Layout_On_Target
+           and then not Known_Static_Esize (Old_Compon)
+         then
+            Set_Esize (New_Compon, Uint_0);
+            Init_Normalized_First_Bit    (New_Compon);
+            Init_Normalized_Position     (New_Compon);
+            Init_Normalized_Position_Max (New_Compon);
+         end if;
 
-      New_Formal : Entity_Id;
-      --  Formal of inherited operation
+         --  We do not want this node marked as Comes_From_Source, since
+         --  otherwise it would get first class status and a separate cross-
+         --  reference line would be generated. Illegitimate children do not
+         --  rate such recognition.
 
-      Visible_Subp : Entity_Id := Parent_Subp;
+         Set_Comes_From_Source (New_Compon, False);
 
-      function Is_Private_Overriding return Boolean;
-      --  If Subp is a private overriding of a visible operation, the inherited
-      --  operation derives from the overridden op (even though its body is the
-      --  overriding one) and the inherited operation is visible now. See
-      --  sem_disp to see the full details of the handling of the overridden
-      --  subprogram, which is removed from the list of primitive operations of
-      --  the type. The overridden subprogram is saved locally in Visible_Subp,
-      --  and used to diagnose abstract operations that need overriding in the
-      --  derived type.
+         --  But it is a real entity, and a birth certificate must be properly
+         --  registered by entering it into the entity list.
 
-      procedure Replace_Type (Id, New_Id : Entity_Id);
-      --  When the type is an anonymous access type, create a new access type
-      --  designating the derived type.
+         Enter_Name (New_Compon);
 
-      procedure Set_Derived_Name;
-      --  This procedure sets the appropriate Chars name for New_Subp. This
-      --  is normally just a copy of the parent name. An exception arises for
-      --  type support subprograms, where the name is changed to reflect the
-      --  name of the derived type, e.g. if type foo is derived from type bar,
-      --  then a procedure barDA is derived with a name fooDA.
+         return New_Compon;
+      end Create_Component;
 
-      ---------------------------
-      -- Is_Private_Overriding --
-      ---------------------------
-
-      function Is_Private_Overriding return Boolean is
-         Prev : Entity_Id;
+      -----------------------
+      -- Is_Variant_Record --
+      -----------------------
 
+      function Is_Variant_Record (T : Entity_Id) return Boolean is
       begin
-         --  If the parent is not a dispatching operation there is no
-         --  need to investigate overridings
+         return Nkind (Parent (T)) = N_Full_Type_Declaration
+           and then Nkind (Type_Definition (Parent (T))) = N_Record_Definition
+           and then Present (Component_List (Type_Definition (Parent (T))))
+           and then
+             Present
+               (Variant_Part (Component_List (Type_Definition (Parent (T)))));
+      end Is_Variant_Record;
 
-         if not Is_Dispatching_Operation (Parent_Subp) then
-            return False;
-         end if;
+   --  Start of processing for Create_Constrained_Components
 
-         --  The visible operation that is overridden is a homonym of the
-         --  parent subprogram. We scan the homonym chain to find the one
-         --  whose alias is the subprogram we are deriving.
+   begin
+      pragma Assert (Subt /= Base_Type (Subt));
+      pragma Assert (Typ = Base_Type (Typ));
 
-         Prev := Current_Entity (Parent_Subp);
-         while Present (Prev) loop
-            if Ekind (Prev) = Ekind (Parent_Subp)
-              and then Alias (Prev) = Parent_Subp
-              and then Scope (Parent_Subp) = Scope (Prev)
-              and then not Is_Hidden (Prev)
-            then
-               Visible_Subp := Prev;
-               return True;
-            end if;
+      Set_First_Entity (Subt, Empty);
+      Set_Last_Entity  (Subt, Empty);
 
-            Prev := Homonym (Prev);
-         end loop;
+      --  Check whether constraint is fully static, in which case we can
+      --  optimize the list of components.
 
-         return False;
-      end Is_Private_Overriding;
+      Discr_Val := First_Elmt (Constraints);
+      while Present (Discr_Val) loop
+         if not Is_OK_Static_Expression (Node (Discr_Val)) then
+            Is_Static := False;
+            exit;
+         end if;
 
-      ------------------
-      -- Replace_Type --
-      ------------------
+         Next_Elmt (Discr_Val);
+      end loop;
 
-      procedure Replace_Type (Id, New_Id : Entity_Id) is
-         Id_Type  : constant Entity_Id := Etype (Id);
-         Acc_Type : Entity_Id;
-         Par      : constant Node_Id := Parent (Derived_Type);
+      Set_Has_Static_Discriminants (Subt, Is_Static);
+
+      Push_Scope (Subt);
+
+      --  Inherit the discriminants of the parent type
+
+      Add_Discriminants : declare
+         Num_Disc : Int;
+         Num_Gird : Int;
 
       begin
-         --  When the type is an anonymous access type, create a new access
-         --  type designating the derived type. This itype must be elaborated
-         --  at the point of the derivation, not on subsequent calls that may
-         --  be out of the proper scope for Gigi, so we insert a reference to
-         --  it after the derivation.
+         Num_Disc := 0;
+         Old_C := First_Discriminant (Typ);
 
-         if Ekind (Id_Type) = E_Anonymous_Access_Type then
-            declare
-               Desig_Typ : Entity_Id := Designated_Type (Id_Type);
+         while Present (Old_C) loop
+            Num_Disc := Num_Disc + 1;
+            New_C := Create_Component (Old_C);
+            Set_Is_Public (New_C, Is_Public (Subt));
+            Next_Discriminant (Old_C);
+         end loop;
 
-            begin
-               if Ekind (Desig_Typ) = E_Record_Type_With_Private
-                 and then Present (Full_View (Desig_Typ))
-                 and then not Is_Private_Type (Parent_Type)
-               then
-                  Desig_Typ := Full_View (Desig_Typ);
-               end if;
+         --  For an untagged derived subtype, the number of discriminants may
+         --  be smaller than the number of inherited discriminants, because
+         --  several of them may be renamed by a single new discriminant or
+         --  constrained. In this case, add the hidden discriminants back into
+         --  the subtype, because they need to be present if the optimizer of
+         --  the GCC 4.x back-end decides to break apart assignments between
+         --  objects using the parent view into member-wise assignments.
 
-               if Base_Type (Desig_Typ) = Base_Type (Parent_Type)
+         Num_Gird := 0;
 
-                  --  Ada 2005 (AI-251): Handle also derivations of abstract
-                  --  interface primitives.
+         if Is_Derived_Type (Typ)
+           and then not Is_Tagged_Type (Typ)
+         then
+            Old_C := First_Stored_Discriminant (Typ);
 
-                 or else (Is_Interface (Desig_Typ)
-                           and then not Is_Class_Wide_Type (Desig_Typ))
-               then
-                  Acc_Type := New_Copy (Id_Type);
-                  Set_Etype (Acc_Type, Acc_Type);
-                  Set_Scope (Acc_Type, New_Subp);
+            while Present (Old_C) loop
+               Num_Gird := Num_Gird + 1;
+               Next_Stored_Discriminant (Old_C);
+            end loop;
+         end if;
 
-                  --  Set size of anonymous access type. If we have an access
-                  --  to an unconstrained array, this is a fat pointer, so it
-                  --  is sizes at twice addtress size.
+         if Num_Gird > Num_Disc then
 
-                  if Is_Array_Type (Desig_Typ)
-                    and then not Is_Constrained (Desig_Typ)
+            --  Find out multiple uses of new discriminants, and add hidden
+            --  components for the extra renamed discriminants. We recognize
+            --  multiple uses through the Corresponding_Discriminant of a
+            --  new discriminant: if it constrains several old discriminants,
+            --  this field points to the last one in the parent type. The
+            --  stored discriminants of the derived type have the same name
+            --  as those of the parent.
+
+            declare
+               Constr    : Elmt_Id;
+               New_Discr : Entity_Id;
+               Old_Discr : Entity_Id;
+
+            begin
+               Constr    := First_Elmt (Stored_Constraint (Typ));
+               Old_Discr := First_Stored_Discriminant (Typ);
+               while Present (Constr) loop
+                  if Is_Entity_Name (Node (Constr))
+                    and then Ekind (Entity (Node (Constr))) = E_Discriminant
                   then
-                     Init_Size (Acc_Type, 2 * System_Address_Size);
+                     New_Discr := Entity (Node (Constr));
 
-                  --  Other cases use a thin pointer
+                     if Chars (Corresponding_Discriminant (New_Discr)) /=
+                        Chars (Old_Discr)
+                     then
+                        --  The new discriminant has been used to rename a
+                        --  subsequent old discriminant. Introduce a shadow
+                        --  component for the current old discriminant.
+
+                        New_C := Create_Component (Old_Discr);
+                        Set_Original_Record_Component (New_C, Old_Discr);
+                     end if;
 
                   else
-                     Init_Size (Acc_Type, System_Address_Size);
-                  end if;
+                     --  The constraint has eliminated the old discriminant.
+                     --  Introduce a shadow component.
 
-                  --  Set remaining characterstics of anonymous access type
+                     New_C := Create_Component (Old_Discr);
+                     Set_Original_Record_Component (New_C, Old_Discr);
+                  end if;
 
-                  Init_Alignment (Acc_Type);
-                  Set_Directly_Designated_Type (Acc_Type, Derived_Type);
+                  Next_Elmt (Constr);
+                  Next_Stored_Discriminant (Old_Discr);
+               end loop;
+            end;
+         end if;
+      end Add_Discriminants;
 
-                  Set_Etype (New_Id, Acc_Type);
-                  Set_Scope (New_Id, New_Subp);
+      if Is_Static
+        and then Is_Variant_Record (Typ)
+      then
+         Collect_Fixed_Components (Typ);
 
-                  --  Create a reference to it
+         Gather_Components (
+           Typ,
+           Component_List (Type_Definition (Parent (Typ))),
+           Governed_By   => Assoc_List,
+           Into          => Comp_List,
+           Report_Errors => Errors);
+         pragma Assert (not Errors);
 
-                  Build_Itype_Reference (Acc_Type, Parent (Derived_Type));
+         Create_All_Components;
 
-               else
-                  Set_Etype (New_Id, Id_Type);
-               end if;
-            end;
+      --  If the subtype declaration is created for a tagged type derivation
+      --  with constraints, we retrieve the record definition of the parent
+      --  type to select the components of the proper variant.
 
-         --  In Ada2012, a formal may have an incomplete type but the type
-         --  derivation that inherits the primitive follows the full view.
+      elsif Is_Static
+        and then Is_Tagged_Type (Typ)
+        and then Nkind (Parent (Typ)) = N_Full_Type_Declaration
+        and then
+          Nkind (Type_Definition (Parent (Typ))) = N_Derived_Type_Definition
+        and then Is_Variant_Record (Parent_Type)
+      then
+         Collect_Fixed_Components (Typ);
 
-         elsif Base_Type (Id_Type) = Base_Type (Parent_Type)
-           or else
-             (Ekind (Id_Type) = E_Record_Type_With_Private
-               and then Present (Full_View (Id_Type))
-               and then
-                 Base_Type (Full_View (Id_Type)) = Base_Type (Parent_Type))
-           or else
-             (Ada_Version >= Ada_2012
-               and then Ekind (Id_Type) = E_Incomplete_Type
-               and then Full_View (Id_Type) = Parent_Type)
-         then
-            --  Constraint checks on formals are generated during expansion,
-            --  based on the signature of the original subprogram. The bounds
-            --  of the derived type are not relevant, and thus we can use
-            --  the base type for the formals. However, the return type may be
-            --  used in a context that requires that the proper static bounds
-            --  be used (a case statement, for example)  and for those cases
-            --  we must use the derived type (first subtype), not its base.
+         Gather_Components
+           (Typ,
+            Component_List (Type_Definition (Parent (Parent_Type))),
+            Governed_By   => Assoc_List,
+            Into          => Comp_List,
+            Report_Errors => Errors);
 
-            --  If the derived_type_definition has no constraints, we know that
-            --  the derived type has the same constraints as the first subtype
-            --  of the parent, and we can also use it rather than its base,
-            --  which can lead to more efficient code.
+         --  Note: previously there was a check at this point that no errors
+         --  were detected. As a consequence of AI05-220 there may be an error
+         --  if an inherited discriminant that controls a variant has a non-
+         --  static constraint.
 
-            if Etype (Id) = Parent_Type then
-               if Is_Scalar_Type (Parent_Type)
-                 and then
-                   Subtypes_Statically_Compatible (Parent_Type, Derived_Type)
-               then
-                  Set_Etype (New_Id, Derived_Type);
+         --  If the tagged derivation has a type extension, collect all the
+         --  new components therein.
 
-               elsif Nkind (Par) = N_Full_Type_Declaration
-                 and then
-                   Nkind (Type_Definition (Par)) = N_Derived_Type_Definition
-                 and then
-                   Is_Entity_Name
-                     (Subtype_Indication (Type_Definition (Par)))
+         if Present (Record_Extension_Part (Type_Definition (Parent (Typ))))
+         then
+            Old_C := First_Component (Typ);
+            while Present (Old_C) loop
+               if Original_Record_Component (Old_C) = Old_C
+                 and then Chars (Old_C) /= Name_uTag
+                 and then Chars (Old_C) /= Name_uParent
                then
-                  Set_Etype (New_Id, Derived_Type);
-
-               else
-                  Set_Etype (New_Id, Base_Type (Derived_Type));
+                  Append_Elmt (Old_C, Comp_List);
                end if;
 
-            else
-               Set_Etype (New_Id, Base_Type (Derived_Type));
-            end if;
-
-         else
-            Set_Etype (New_Id, Etype (Id));
+               Next_Component (Old_C);
+            end loop;
          end if;
-      end Replace_Type;
-
-      ----------------------
-      -- Set_Derived_Name --
-      ----------------------
 
-      procedure Set_Derived_Name is
-         Nm : constant TSS_Name_Type := Get_TSS_Name (Parent_Subp);
-      begin
-         if Nm = TSS_Null then
-            Set_Chars (New_Subp, Chars (Parent_Subp));
-         else
-            Set_Chars (New_Subp, Make_TSS_Name (Base_Type (Derived_Type), Nm));
-         end if;
-      end Set_Derived_Name;
+         Create_All_Components;
 
-   --  Start of processing for Derive_Subprogram
+      else
+         --  If discriminants are not static, or if this is a multi-level type
+         --  extension, we have to include all components of the parent type.
 
-   begin
-      New_Subp :=
-         New_Entity (Nkind (Parent_Subp), Sloc (Derived_Type));
-      Set_Ekind (New_Subp, Ekind (Parent_Subp));
-      Set_Contract (New_Subp, Make_Contract (Sloc (New_Subp)));
+         Old_C := First_Component (Typ);
+         while Present (Old_C) loop
+            New_C := Create_Component (Old_C);
 
-      --  Check whether the inherited subprogram is a private operation that
-      --  should be inherited but not yet made visible. Such subprograms can
-      --  become visible at a later point (e.g., the private part of a public
-      --  child unit) via Declare_Inherited_Private_Subprograms. If the
-      --  following predicate is true, then this is not such a private
-      --  operation and the subprogram simply inherits the name of the parent
-      --  subprogram. Note the special check for the names of controlled
-      --  operations, which are currently exempted from being inherited with
-      --  a hidden name because they must be findable for generation of
-      --  implicit run-time calls.
+            Set_Etype
+              (New_C,
+               Constrain_Component_Type
+                 (Old_C, Subt, Decl_Node, Typ, Constraints));
+            Set_Is_Public (New_C, Is_Public (Subt));
 
-      if not Is_Hidden (Parent_Subp)
-        or else Is_Internal (Parent_Subp)
-        or else Is_Private_Overriding
-        or else Is_Internal_Name (Chars (Parent_Subp))
-        or else Nam_In (Chars (Parent_Subp), Name_Initialize,
-                                             Name_Adjust,
-                                             Name_Finalize)
-      then
-         Set_Derived_Name;
+            Next_Component (Old_C);
+         end loop;
+      end if;
 
-      --  An inherited dispatching equality will be overridden by an internally
-      --  generated one, or by an explicit one, so preserve its name and thus
-      --  its entry in the dispatch table. Otherwise, if Parent_Subp is a
-      --  private operation it may become invisible if the full view has
-      --  progenitors, and the dispatch table will be malformed.
-      --  We check that the type is limited to handle the anomalous declaration
-      --  of Limited_Controlled, which is derived from a non-limited type, and
-      --  which is handled specially elsewhere as well.
+      End_Scope;
+   end Create_Constrained_Components;
 
-      elsif Chars (Parent_Subp) = Name_Op_Eq
-        and then Is_Dispatching_Operation (Parent_Subp)
-        and then Etype (Parent_Subp) = Standard_Boolean
-        and then not Is_Limited_Type (Etype (First_Formal (Parent_Subp)))
-        and then
-          Etype (First_Formal (Parent_Subp)) =
-            Etype (Next_Formal (First_Formal (Parent_Subp)))
-      then
-         Set_Derived_Name;
+   ------------------------------------------
+   -- Decimal_Fixed_Point_Type_Declaration --
+   ------------------------------------------
 
-      --  If parent is hidden, this can be a regular derivation if the
-      --  parent is immediately visible in a non-instantiating context,
-      --  or if we are in the private part of an instance. This test
-      --  should still be refined ???
+   procedure Decimal_Fixed_Point_Type_Declaration
+     (T   : Entity_Id;
+      Def : Node_Id)
+   is
+      Loc           : constant Source_Ptr := Sloc (Def);
+      Digs_Expr     : constant Node_Id    := Digits_Expression (Def);
+      Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
+      Implicit_Base : Entity_Id;
+      Digs_Val      : Uint;
+      Delta_Val     : Ureal;
+      Scale_Val     : Uint;
+      Bound_Val     : Ureal;
 
-      --  The test for In_Instance_Not_Visible avoids inheriting the derived
-      --  operation as a non-visible operation in cases where the parent
-      --  subprogram might not be visible now, but was visible within the
-      --  original generic, so it would be wrong to make the inherited
-      --  subprogram non-visible now. (Not clear if this test is fully
-      --  correct; are there any cases where we should declare the inherited
-      --  operation as not visible to avoid it being overridden, e.g., when
-      --  the parent type is a generic actual with private primitives ???)
+   begin
+      Check_SPARK_05_Restriction
+        ("decimal fixed point type is not allowed", Def);
+      Check_Restriction (No_Fixed_Point, Def);
 
-      --  (they should be treated the same as other private inherited
-      --  subprograms, but it's not clear how to do this cleanly). ???
+      --  Create implicit base type
 
-      elsif (In_Open_Scopes (Scope (Base_Type (Parent_Type)))
-              and then Is_Immediately_Visible (Parent_Subp)
-              and then not In_Instance)
-        or else In_Instance_Not_Visible
-      then
-         Set_Derived_Name;
+      Implicit_Base :=
+        Create_Itype (E_Decimal_Fixed_Point_Type, Parent (Def), T, 'B');
+      Set_Etype (Implicit_Base, Implicit_Base);
 
-      --  Ada 2005 (AI-251): Regular derivation if the parent subprogram
-      --  overrides an interface primitive because interface primitives
-      --  must be visible in the partial view of the parent (RM 7.3 (7.3/2))
+      --  Analyze and process delta expression
 
-      elsif Ada_Version >= Ada_2005
-         and then Is_Dispatching_Operation (Parent_Subp)
-         and then Covers_Some_Interface (Parent_Subp)
-      then
-         Set_Derived_Name;
+      Analyze_And_Resolve (Delta_Expr, Universal_Real);
 
-      --  Otherwise, the type is inheriting a private operation, so enter
-      --  it with a special name so it can't be overridden.
+      Check_Delta_Expression (Delta_Expr);
+      Delta_Val := Expr_Value_R (Delta_Expr);
 
-      else
-         Set_Chars (New_Subp, New_External_Name (Chars (Parent_Subp), 'P'));
-      end if;
+      --  Check delta is power of 10, and determine scale value from it
 
-      Set_Parent (New_Subp, Parent (Derived_Type));
+      declare
+         Val : Ureal;
 
-      if Present (Actual_Subp) then
-         Replace_Type (Actual_Subp, New_Subp);
-      else
-         Replace_Type (Parent_Subp, New_Subp);
-      end if;
+      begin
+         Scale_Val := Uint_0;
+         Val := Delta_Val;
 
-      Conditional_Delay (New_Subp, Parent_Subp);
+         if Val < Ureal_1 then
+            while Val < Ureal_1 loop
+               Val := Val * Ureal_10;
+               Scale_Val := Scale_Val + 1;
+            end loop;
 
-      --  If we are creating a renaming for a primitive operation of an
-      --  actual of a generic derived type, we must examine the signature
-      --  of the actual primitive, not that of the generic formal, which for
-      --  example may be an interface. However the name and initial value
-      --  of the inherited operation are those of the formal primitive.
+            if Scale_Val > 18 then
+               Error_Msg_N ("scale exceeds maximum value of 18", Def);
+               Scale_Val := UI_From_Int (+18);
+            end if;
 
-      Formal := First_Formal (Parent_Subp);
+         else
+            while Val > Ureal_1 loop
+               Val := Val / Ureal_10;
+               Scale_Val := Scale_Val - 1;
+            end loop;
 
-      if Present (Actual_Subp) then
-         Formal_Of_Actual := First_Formal (Actual_Subp);
-      else
-         Formal_Of_Actual := Empty;
-      end if;
+            if Scale_Val < -18 then
+               Error_Msg_N ("scale is less than minimum value of -18", Def);
+               Scale_Val := UI_From_Int (-18);
+            end if;
+         end if;
 
-      while Present (Formal) loop
-         New_Formal := New_Copy (Formal);
+         if Val /= Ureal_1 then
+            Error_Msg_N ("delta expression must be a power of 10", Def);
+            Delta_Val := Ureal_10 ** (-Scale_Val);
+         end if;
+      end;
 
-         --  Normally we do not go copying parents, but in the case of
-         --  formals, we need to link up to the declaration (which is the
-         --  parameter specification), and it is fine to link up to the
-         --  original formal's parameter specification in this case.
+      --  Set delta, scale and small (small = delta for decimal type)
 
-         Set_Parent (New_Formal, Parent (Formal));
-         Append_Entity (New_Formal, New_Subp);
+      Set_Delta_Value (Implicit_Base, Delta_Val);
+      Set_Scale_Value (Implicit_Base, Scale_Val);
+      Set_Small_Value (Implicit_Base, Delta_Val);
 
-         if Present (Formal_Of_Actual) then
-            Replace_Type (Formal_Of_Actual, New_Formal);
-            Next_Formal (Formal_Of_Actual);
-         else
-            Replace_Type (Formal, New_Formal);
-         end if;
+      --  Analyze and process digits expression
 
-         Next_Formal (Formal);
-      end loop;
+      Analyze_And_Resolve (Digs_Expr, Any_Integer);
+      Check_Digits_Expression (Digs_Expr);
+      Digs_Val := Expr_Value (Digs_Expr);
 
-      --  If this derivation corresponds to a tagged generic actual, then
-      --  primitive operations rename those of the actual. Otherwise the
-      --  primitive operations rename those of the parent type, If the parent
-      --  renames an intrinsic operator, so does the new subprogram. We except
-      --  concatenation, which is always properly typed, and does not get
-      --  expanded as other intrinsic operations.
+      if Digs_Val > 18 then
+         Digs_Val := UI_From_Int (+18);
+         Error_Msg_N ("digits value out of range, maximum is 18", Digs_Expr);
+      end if;
 
-      if No (Actual_Subp) then
-         if Is_Intrinsic_Subprogram (Parent_Subp) then
-            Set_Is_Intrinsic_Subprogram (New_Subp);
+      Set_Digits_Value (Implicit_Base, Digs_Val);
+      Bound_Val := UR_From_Uint (10 ** Digs_Val - 1) * Delta_Val;
 
-            if Present (Alias (Parent_Subp))
-              and then Chars (Parent_Subp) /= Name_Op_Concat
-            then
-               Set_Alias (New_Subp, Alias (Parent_Subp));
-            else
-               Set_Alias (New_Subp, Parent_Subp);
-            end if;
+      --  Set range of base type from digits value for now. This will be
+      --  expanded to represent the true underlying base range by Freeze.
 
-         else
-            Set_Alias (New_Subp, Parent_Subp);
-         end if;
+      Set_Fixed_Range (Implicit_Base, Loc, -Bound_Val, Bound_Val);
 
-      else
-         Set_Alias (New_Subp, Actual_Subp);
-      end if;
+      --  Note: We leave size as zero for now, size will be set at freeze
+      --  time. We have to do this for ordinary fixed-point, because the size
+      --  depends on the specified small, and we might as well do the same for
+      --  decimal fixed-point.
 
-      --  Derived subprograms of a tagged type must inherit the convention
-      --  of the parent subprogram (a requirement of AI-117). Derived
-      --  subprograms of untagged types simply get convention Ada by default.
+      pragma Assert (Esize (Implicit_Base) = Uint_0);
 
-      --  If the derived type is a tagged generic formal type with unknown
-      --  discriminants, its convention is intrinsic (RM 6.3.1 (8)).
+      --  If there are bounds given in the declaration use them as the
+      --  bounds of the first named subtype.
 
-      --  However, if the type is derived from a generic formal, the further
-      --  inherited subprogram has the convention of the non-generic ancestor.
-      --  Otherwise there would be no way to override the operation.
-      --  (This is subject to forthcoming ARG discussions).
+      if Present (Real_Range_Specification (Def)) then
+         declare
+            RRS      : constant Node_Id := Real_Range_Specification (Def);
+            Low      : constant Node_Id := Low_Bound (RRS);
+            High     : constant Node_Id := High_Bound (RRS);
+            Low_Val  : Ureal;
+            High_Val : Ureal;
 
-      if Is_Tagged_Type (Derived_Type) then
-         if Is_Generic_Type (Derived_Type)
-           and then Has_Unknown_Discriminants (Derived_Type)
-         then
-            Set_Convention (New_Subp, Convention_Intrinsic);
+         begin
+            Analyze_And_Resolve (Low, Any_Real);
+            Analyze_And_Resolve (High, Any_Real);
+            Check_Real_Bound (Low);
+            Check_Real_Bound (High);
+            Low_Val := Expr_Value_R (Low);
+            High_Val := Expr_Value_R (High);
 
-         else
-            if Is_Generic_Type (Parent_Type)
-              and then Has_Unknown_Discriminants (Parent_Type)
-            then
-               Set_Convention (New_Subp, Convention (Alias (Parent_Subp)));
-            else
-               Set_Convention (New_Subp, Convention (Parent_Subp));
+            if Low_Val < (-Bound_Val) then
+               Error_Msg_N
+                 ("range low bound too small for digits value", Low);
+               Low_Val := -Bound_Val;
             end if;
-         end if;
-      end if;
 
-      --  Predefined controlled operations retain their name even if the parent
-      --  is hidden (see above), but they are not primitive operations if the
-      --  ancestor is not visible, for example if the parent is a private
-      --  extension completed with a controlled extension. Note that a full
-      --  type that is controlled can break privacy: the flag Is_Controlled is
-      --  set on both views of the type.
+            if High_Val > Bound_Val then
+               Error_Msg_N
+                 ("range high bound too large for digits value", High);
+               High_Val := Bound_Val;
+            end if;
 
-      if Is_Controlled (Parent_Type)
-        and then Nam_In (Chars (Parent_Subp), Name_Initialize,
-                                              Name_Adjust,
-                                              Name_Finalize)
-        and then Is_Hidden (Parent_Subp)
-        and then not Is_Visibly_Controlled (Parent_Type)
-      then
-         Set_Is_Hidden (New_Subp);
-      end if;
+            Set_Fixed_Range (T, Loc, Low_Val, High_Val);
+         end;
 
-      Set_Is_Imported (New_Subp, Is_Imported (Parent_Subp));
-      Set_Is_Exported (New_Subp, Is_Exported (Parent_Subp));
+      --  If no explicit range, use range that corresponds to given
+      --  digits value. This will end up as the final range for the
+      --  first subtype.
 
-      if Ekind (Parent_Subp) = E_Procedure then
-         Set_Is_Valued_Procedure
-           (New_Subp, Is_Valued_Procedure (Parent_Subp));
       else
-         Set_Has_Controlling_Result
-           (New_Subp, Has_Controlling_Result (Parent_Subp));
+         Set_Fixed_Range (T, Loc, -Bound_Val, Bound_Val);
       end if;
 
-      --  No_Return must be inherited properly. If this is overridden in the
-      --  case of a dispatching operation, then a check is made in Sem_Disp
-      --  that the overriding operation is also No_Return (no such check is
-      --  required for the case of non-dispatching operation.
+      --  Complete entity for first subtype. The inheritance of the rep item
+      --  chain ensures that SPARK-related pragmas are not clobbered when the
+      --  decimal fixed point type acts as a full view of a private type.
 
-      Set_No_Return (New_Subp, No_Return (Parent_Subp));
+      Set_Ekind              (T, E_Decimal_Fixed_Point_Subtype);
+      Set_Etype              (T, Implicit_Base);
+      Set_Size_Info          (T, Implicit_Base);
+      Inherit_Rep_Item_Chain (T, Implicit_Base);
+      Set_Digits_Value       (T, Digs_Val);
+      Set_Delta_Value        (T, Delta_Val);
+      Set_Small_Value        (T, Delta_Val);
+      Set_Scale_Value        (T, Scale_Val);
+      Set_Is_Constrained     (T);
+   end Decimal_Fixed_Point_Type_Declaration;
 
-      --  A derived function with a controlling result is abstract. If the
-      --  Derived_Type is a nonabstract formal generic derived type, then
-      --  inherited operations are not abstract: the required check is done at
-      --  instantiation time. If the derivation is for a generic actual, the
-      --  function is not abstract unless the actual is.
+   -----------------------------------
+   -- Derive_Progenitor_Subprograms --
+   -----------------------------------
 
-      if Is_Generic_Type (Derived_Type)
-        and then not Is_Abstract_Type (Derived_Type)
-      then
-         null;
+   procedure Derive_Progenitor_Subprograms
+     (Parent_Type : Entity_Id;
+      Tagged_Type : Entity_Id)
+   is
+      E          : Entity_Id;
+      Elmt       : Elmt_Id;
+      Iface      : Entity_Id;
+      Iface_Elmt : Elmt_Id;
+      Iface_Subp : Entity_Id;
+      New_Subp   : Entity_Id := Empty;
+      Prim_Elmt  : Elmt_Id;
+      Subp       : Entity_Id;
+      Typ        : Entity_Id;
 
-      --  Ada 2005 (AI-228): Calculate the "require overriding" and "abstract"
-      --  properties of the subprogram, as defined in RM-3.9.3(4/2-6/2).
+   begin
+      pragma Assert (Ada_Version >= Ada_2005
+        and then Is_Record_Type (Tagged_Type)
+        and then Is_Tagged_Type (Tagged_Type)
+        and then Has_Interfaces (Tagged_Type));
 
-      elsif Ada_Version >= Ada_2005
-        and then (Is_Abstract_Subprogram (Alias (New_Subp))
-                   or else (Is_Tagged_Type (Derived_Type)
-                             and then Etype (New_Subp) = Derived_Type
-                             and then not Is_Null_Extension (Derived_Type))
-                   or else (Is_Tagged_Type (Derived_Type)
-                             and then Ekind (Etype (New_Subp)) =
-                                                       E_Anonymous_Access_Type
-                             and then Designated_Type (Etype (New_Subp)) =
-                                                        Derived_Type
-                             and then not Is_Null_Extension (Derived_Type)))
-        and then No (Actual_Subp)
-      then
-         if not Is_Tagged_Type (Derived_Type)
-           or else Is_Abstract_Type (Derived_Type)
-           or else Is_Abstract_Subprogram (Alias (New_Subp))
-         then
-            Set_Is_Abstract_Subprogram (New_Subp);
-         else
-            Set_Requires_Overriding (New_Subp);
-         end if;
+      --  Step 1: Transfer to the full-view primitives associated with the
+      --  partial-view that cover interface primitives. Conceptually this
+      --  work should be done later by Process_Full_View; done here to
+      --  simplify its implementation at later stages. It can be safely
+      --  done here because interfaces must be visible in the partial and
+      --  private view (RM 7.3(7.3/2)).
 
-      elsif Ada_Version < Ada_2005
-        and then (Is_Abstract_Subprogram (Alias (New_Subp))
-                   or else (Is_Tagged_Type (Derived_Type)
-                             and then Etype (New_Subp) = Derived_Type
-                             and then No (Actual_Subp)))
-      then
-         Set_Is_Abstract_Subprogram (New_Subp);
+      --  Small optimization: This work is only required if the parent may
+      --  have entities whose Alias attribute reference an interface primitive.
+      --  Such a situation may occur if the parent is an abstract type and the
+      --  primitive has not been yet overridden or if the parent is a generic
+      --  formal type covering interfaces.
 
-      --  AI05-0097 : an inherited operation that dispatches on result is
-      --  abstract if the derived type is abstract, even if the parent type
-      --  is concrete and the derived type is a null extension.
+      --  If the tagged type is not abstract, it cannot have abstract
+      --  primitives (the only entities in the list of primitives of
+      --  non-abstract tagged types that can reference abstract primitives
+      --  through its Alias attribute are the internal entities that have
+      --  attribute Interface_Alias, and these entities are generated later
+      --  by Add_Internal_Interface_Entities).
 
-      elsif Has_Controlling_Result (Alias (New_Subp))
-        and then Is_Abstract_Type (Etype (New_Subp))
+      if In_Private_Part (Current_Scope)
+        and then (Is_Abstract_Type (Parent_Type)
+                    or else
+                  Is_Generic_Type  (Parent_Type))
       then
-         Set_Is_Abstract_Subprogram (New_Subp);
+         Elmt := First_Elmt (Primitive_Operations (Tagged_Type));
+         while Present (Elmt) loop
+            Subp := Node (Elmt);
 
-      --  Finally, if the parent type is abstract we must verify that all
-      --  inherited operations are either non-abstract or overridden, or that
-      --  the derived type itself is abstract (this check is performed at the
-      --  end of a package declaration, in Check_Abstract_Overriding). A
-      --  private overriding in the parent type will not be visible in the
-      --  derivation if we are not in an inner package or in a child unit of
-      --  the parent type, in which case the abstractness of the inherited
-      --  operation is carried to the new subprogram.
+            --  At this stage it is not possible to have entities in the list
+            --  of primitives that have attribute Interface_Alias.
 
-      elsif Is_Abstract_Type (Parent_Type)
-        and then not In_Open_Scopes (Scope (Parent_Type))
-        and then Is_Private_Overriding
-        and then Is_Abstract_Subprogram (Visible_Subp)
-      then
-         if No (Actual_Subp) then
-            Set_Alias (New_Subp, Visible_Subp);
-            Set_Is_Abstract_Subprogram (New_Subp, True);
+            pragma Assert (No (Interface_Alias (Subp)));
 
-         else
-            --  If this is a derivation for an instance of a formal derived
-            --  type, abstractness comes from the primitive operation of the
-            --  actual, not from the operation inherited from the ancestor.
+            Typ := Find_Dispatching_Type (Ultimate_Alias (Subp));
 
-            Set_Is_Abstract_Subprogram
-              (New_Subp, Is_Abstract_Subprogram (Actual_Subp));
-         end if;
-      end if;
+            if Is_Interface (Typ) then
+               E := Find_Primitive_Covering_Interface
+                      (Tagged_Type => Tagged_Type,
+                       Iface_Prim  => Subp);
 
-      New_Overloaded_Entity (New_Subp, Derived_Type);
+               if Present (E)
+                 and then Find_Dispatching_Type (Ultimate_Alias (E)) /= Typ
+               then
+                  Replace_Elmt (Elmt, E);
+                  Remove_Homonym (Subp);
+               end if;
+            end if;
 
-      --  Check for case of a derived subprogram for the instantiation of a
-      --  formal derived tagged type, if so mark the subprogram as dispatching
-      --  and inherit the dispatching attributes of the actual subprogram. The
-      --  derived subprogram is effectively renaming of the actual subprogram,
-      --  so it needs to have the same attributes as the actual.
+            Next_Elmt (Elmt);
+         end loop;
+      end if;
 
-      if Present (Actual_Subp)
-        and then Is_Dispatching_Operation (Actual_Subp)
-      then
-         Set_Is_Dispatching_Operation (New_Subp);
+      --  Step 2: Add primitives of progenitors that are not implemented by
+      --  parents of Tagged_Type.
 
-         if Present (DTC_Entity (Actual_Subp)) then
-            Set_DTC_Entity (New_Subp, DTC_Entity (Actual_Subp));
-            Set_DT_Position (New_Subp, DT_Position (Actual_Subp));
-         end if;
-      end if;
+      if Present (Interfaces (Base_Type (Tagged_Type))) then
+         Iface_Elmt := First_Elmt (Interfaces (Base_Type (Tagged_Type)));
+         while Present (Iface_Elmt) loop
+            Iface := Node (Iface_Elmt);
 
-      --  Indicate that a derived subprogram does not require a body and that
-      --  it does not require processing of default expressions.
+            Prim_Elmt := First_Elmt (Primitive_Operations (Iface));
+            while Present (Prim_Elmt) loop
+               Iface_Subp := Node (Prim_Elmt);
 
-      Set_Has_Completion (New_Subp);
-      Set_Default_Expressions_Processed (New_Subp);
+               --  Exclude derivation of predefined primitives except those
+               --  that come from source, or are inherited from one that comes
+               --  from source. Required to catch declarations of equality
+               --  operators of interfaces. For example:
 
-      if Ekind (New_Subp) = E_Function then
-         Set_Mechanism (New_Subp, Mechanism (Parent_Subp));
-      end if;
-   end Derive_Subprogram;
+               --     type Iface is interface;
+               --     function "=" (Left, Right : Iface) return Boolean;
 
-   ------------------------
-   -- Derive_Subprograms --
-   ------------------------
+               if not Is_Predefined_Dispatching_Operation (Iface_Subp)
+                 or else Comes_From_Source (Ultimate_Alias (Iface_Subp))
+               then
+                  E := Find_Primitive_Covering_Interface
+                         (Tagged_Type => Tagged_Type,
+                          Iface_Prim  => Iface_Subp);
 
-   procedure Derive_Subprograms
-     (Parent_Type    : Entity_Id;
-      Derived_Type   : Entity_Id;
-      Generic_Actual : Entity_Id := Empty)
-   is
-      Op_List : constant Elist_Id :=
-                  Collect_Primitive_Operations (Parent_Type);
+                  --  If not found we derive a new primitive leaving its alias
+                  --  attribute referencing the interface primitive.
 
-      function Check_Derived_Type return Boolean;
-      --  Check that all the entities derived from Parent_Type are found in
-      --  the list of primitives of Derived_Type exactly in the same order.
+                  if No (E) then
+                     Derive_Subprogram
+                       (New_Subp, Iface_Subp, Tagged_Type, Iface);
 
-      procedure Derive_Interface_Subprogram
-        (New_Subp    : in out Entity_Id;
-         Subp        : Entity_Id;
-         Actual_Subp : Entity_Id);
-      --  Derive New_Subp from the ultimate alias of the parent subprogram Subp
-      --  (which is an interface primitive). If Generic_Actual is present then
-      --  Actual_Subp is the actual subprogram corresponding with the generic
-      --  subprogram Subp.
+                  --  Ada 2012 (AI05-0197): If the covering primitive's name
+                  --  differs from the name of the interface primitive then it
+                  --  is a private primitive inherited from a parent type. In
+                  --  such case, given that Tagged_Type covers the interface,
+                  --  the inherited private primitive becomes visible. For such
+                  --  purpose we add a new entity that renames the inherited
+                  --  private primitive.
 
-      function Check_Derived_Type return Boolean is
-         E        : Entity_Id;
-         Elmt     : Elmt_Id;
-         List     : Elist_Id;
-         New_Subp : Entity_Id;
-         Op_Elmt  : Elmt_Id;
-         Subp     : Entity_Id;
+                  elsif Chars (E) /= Chars (Iface_Subp) then
+                     pragma Assert (Has_Suffix (E, 'P'));
+                     Derive_Subprogram
+                       (New_Subp, Iface_Subp, Tagged_Type, Iface);
+                     Set_Alias (New_Subp, E);
+                     Set_Is_Abstract_Subprogram (New_Subp,
+                       Is_Abstract_Subprogram (E));
 
-      begin
-         --  Traverse list of entities in the current scope searching for
-         --  an incomplete type whose full-view is derived type
+                  --  Propagate to the full view interface entities associated
+                  --  with the partial view.
 
-         E := First_Entity (Scope (Derived_Type));
-         while Present (E) and then E /= Derived_Type loop
-            if Ekind (E) = E_Incomplete_Type
-              and then Present (Full_View (E))
-              and then Full_View (E) = Derived_Type
-            then
-               --  Disable this test if Derived_Type completes an incomplete
-               --  type because in such case more primitives can be added
-               --  later to the list of primitives of Derived_Type by routine
-               --  Process_Incomplete_Dependents
+                  elsif In_Private_Part (Current_Scope)
+                    and then Present (Alias (E))
+                    and then Alias (E) = Iface_Subp
+                    and then
+                      List_Containing (Parent (E)) /=
+                        Private_Declarations
+                          (Specification
+                            (Unit_Declaration_Node (Current_Scope)))
+                  then
+                     Append_Elmt (E, Primitive_Operations (Tagged_Type));
+                  end if;
+               end if;
 
-               return True;
-            end if;
+               Next_Elmt (Prim_Elmt);
+            end loop;
 
-            E := Next_Entity (E);
+            Next_Elmt (Iface_Elmt);
          end loop;
+      end if;
+   end Derive_Progenitor_Subprograms;
 
-         List := Collect_Primitive_Operations (Derived_Type);
-         Elmt := First_Elmt (List);
+   -----------------------
+   -- Derive_Subprogram --
+   -----------------------
 
-         Op_Elmt := First_Elmt (Op_List);
-         while Present (Op_Elmt) loop
-            Subp     := Node (Op_Elmt);
-            New_Subp := Node (Elmt);
+   procedure Derive_Subprogram
+     (New_Subp     : in out Entity_Id;
+      Parent_Subp  : Entity_Id;
+      Derived_Type : Entity_Id;
+      Parent_Type  : Entity_Id;
+      Actual_Subp  : Entity_Id := Empty)
+   is
+      Formal : Entity_Id;
+      --  Formal parameter of parent primitive operation
 
-            --  At this early stage Derived_Type has no entities with attribute
-            --  Interface_Alias. In addition, such primitives are always
-            --  located at the end of the list of primitives of Parent_Type.
-            --  Therefore, if found we can safely stop processing pending
-            --  entities.
+      Formal_Of_Actual : Entity_Id;
+      --  Formal parameter of actual operation, when the derivation is to
+      --  create a renaming for a primitive operation of an actual in an
+      --  instantiation.
 
-            exit when Present (Interface_Alias (Subp));
+      New_Formal : Entity_Id;
+      --  Formal of inherited operation
 
-            --  Handle hidden entities
+      Visible_Subp : Entity_Id := Parent_Subp;
 
-            if not Is_Predefined_Dispatching_Operation (Subp)
-              and then Is_Hidden (Subp)
-            then
-               if Present (New_Subp)
-                 and then Primitive_Names_Match (Subp, New_Subp)
-               then
-                  Next_Elmt (Elmt);
-               end if;
+      function Is_Private_Overriding return Boolean;
+      --  If Subp is a private overriding of a visible operation, the inherited
+      --  operation derives from the overridden op (even though its body is the
+      --  overriding one) and the inherited operation is visible now. See
+      --  sem_disp to see the full details of the handling of the overridden
+      --  subprogram, which is removed from the list of primitive operations of
+      --  the type. The overridden subprogram is saved locally in Visible_Subp,
+      --  and used to diagnose abstract operations that need overriding in the
+      --  derived type.
 
-            else
-               if not Present (New_Subp)
-                 or else Ekind (Subp) /= Ekind (New_Subp)
-                 or else not Primitive_Names_Match (Subp, New_Subp)
-               then
-                  return False;
-               end if;
+      procedure Replace_Type (Id, New_Id : Entity_Id);
+      --  When the type is an anonymous access type, create a new access type
+      --  designating the derived type.
 
-               Next_Elmt (Elmt);
+      procedure Set_Derived_Name;
+      --  This procedure sets the appropriate Chars name for New_Subp. This
+      --  is normally just a copy of the parent name. An exception arises for
+      --  type support subprograms, where the name is changed to reflect the
+      --  name of the derived type, e.g. if type foo is derived from type bar,
+      --  then a procedure barDA is derived with a name fooDA.
+
+      ---------------------------
+      -- Is_Private_Overriding --
+      ---------------------------
+
+      function Is_Private_Overriding return Boolean is
+         Prev : Entity_Id;
+
+      begin
+         --  If the parent is not a dispatching operation there is no
+         --  need to investigate overridings
+
+         if not Is_Dispatching_Operation (Parent_Subp) then
+            return False;
+         end if;
+
+         --  The visible operation that is overridden is a homonym of the
+         --  parent subprogram. We scan the homonym chain to find the one
+         --  whose alias is the subprogram we are deriving.
+
+         Prev := Current_Entity (Parent_Subp);
+         while Present (Prev) loop
+            if Ekind (Prev) = Ekind (Parent_Subp)
+              and then Alias (Prev) = Parent_Subp
+              and then Scope (Parent_Subp) = Scope (Prev)
+              and then not Is_Hidden (Prev)
+            then
+               Visible_Subp := Prev;
+               return True;
             end if;
 
-            Next_Elmt (Op_Elmt);
+            Prev := Homonym (Prev);
          end loop;
 
-         return True;
-      end Check_Derived_Type;
+         return False;
+      end Is_Private_Overriding;
 
-      ---------------------------------
-      -- Derive_Interface_Subprogram --
-      ---------------------------------
+      ------------------
+      -- Replace_Type --
+      ------------------
 
-      procedure Derive_Interface_Subprogram
-        (New_Subp    : in out Entity_Id;
-         Subp        : Entity_Id;
-         Actual_Subp : Entity_Id)
-      is
-         Iface_Subp : constant Entity_Id := Ultimate_Alias (Subp);
-         Iface_Type : constant Entity_Id := Find_Dispatching_Type (Iface_Subp);
+      procedure Replace_Type (Id, New_Id : Entity_Id) is
+         Id_Type  : constant Entity_Id := Etype (Id);
+         Acc_Type : Entity_Id;
+         Par      : constant Node_Id := Parent (Derived_Type);
 
       begin
-         pragma Assert (Is_Interface (Iface_Type));
+         --  When the type is an anonymous access type, create a new access
+         --  type designating the derived type. This itype must be elaborated
+         --  at the point of the derivation, not on subsequent calls that may
+         --  be out of the proper scope for Gigi, so we insert a reference to
+         --  it after the derivation.
 
-         Derive_Subprogram
-           (New_Subp     => New_Subp,
-            Parent_Subp  => Iface_Subp,
-            Derived_Type => Derived_Type,
-            Parent_Type  => Iface_Type,
-            Actual_Subp  => Actual_Subp);
+         if Ekind (Id_Type) = E_Anonymous_Access_Type then
+            declare
+               Desig_Typ : Entity_Id := Designated_Type (Id_Type);
 
-         --  Given that this new interface entity corresponds with a primitive
-         --  of the parent that was not overridden we must leave it associated
-         --  with its parent primitive to ensure that it will share the same
-         --  dispatch table slot when overridden.
+            begin
+               if Ekind (Desig_Typ) = E_Record_Type_With_Private
+                 and then Present (Full_View (Desig_Typ))
+                 and then not Is_Private_Type (Parent_Type)
+               then
+                  Desig_Typ := Full_View (Desig_Typ);
+               end if;
 
-         if No (Actual_Subp) then
-            Set_Alias (New_Subp, Subp);
+               if Base_Type (Desig_Typ) = Base_Type (Parent_Type)
 
-         --  For instantiations this is not needed since the previous call to
-         --  Derive_Subprogram leaves the entity well decorated.
+                  --  Ada 2005 (AI-251): Handle also derivations of abstract
+                  --  interface primitives.
 
-         else
-            pragma Assert (Alias (New_Subp) = Actual_Subp);
-            null;
-         end if;
-      end Derive_Interface_Subprogram;
+                 or else (Is_Interface (Desig_Typ)
+                           and then not Is_Class_Wide_Type (Desig_Typ))
+               then
+                  Acc_Type := New_Copy (Id_Type);
+                  Set_Etype (Acc_Type, Acc_Type);
+                  Set_Scope (Acc_Type, New_Subp);
 
-      --  Local variables
+                  --  Set size of anonymous access type. If we have an access
+                  --  to an unconstrained array, this is a fat pointer, so it
+                  --  is sizes at twice addtress size.
 
-      Alias_Subp   : Entity_Id;
-      Act_List     : Elist_Id;
-      Act_Elmt     : Elmt_Id;
-      Act_Subp     : Entity_Id := Empty;
-      Elmt         : Elmt_Id;
-      Need_Search  : Boolean   := False;
-      New_Subp     : Entity_Id := Empty;
-      Parent_Base  : Entity_Id;
-      Subp         : Entity_Id;
+                  if Is_Array_Type (Desig_Typ)
+                    and then not Is_Constrained (Desig_Typ)
+                  then
+                     Init_Size (Acc_Type, 2 * System_Address_Size);
 
-   --  Start of processing for Derive_Subprograms
+                  --  Other cases use a thin pointer
 
-   begin
-      if Ekind (Parent_Type) = E_Record_Type_With_Private
-        and then Has_Discriminants (Parent_Type)
-        and then Present (Full_View (Parent_Type))
-      then
-         Parent_Base := Full_View (Parent_Type);
-      else
-         Parent_Base := Parent_Type;
-      end if;
+                  else
+                     Init_Size (Acc_Type, System_Address_Size);
+                  end if;
 
-      if Present (Generic_Actual) then
-         Act_List := Collect_Primitive_Operations (Generic_Actual);
-         Act_Elmt := First_Elmt (Act_List);
-      else
-         Act_List := No_Elist;
-         Act_Elmt := No_Elmt;
-      end if;
+                  --  Set remaining characterstics of anonymous access type
 
-      --  Derive primitives inherited from the parent. Note that if the generic
-      --  actual is present, this is not really a type derivation, it is a
-      --  completion within an instance.
+                  Init_Alignment (Acc_Type);
+                  Set_Directly_Designated_Type (Acc_Type, Derived_Type);
 
-      --  Case 1: Derived_Type does not implement interfaces
+                  Set_Etype (New_Id, Acc_Type);
+                  Set_Scope (New_Id, New_Subp);
 
-      if not Is_Tagged_Type (Derived_Type)
-        or else (not Has_Interfaces (Derived_Type)
-                  and then not (Present (Generic_Actual)
-                                 and then Has_Interfaces (Generic_Actual)))
-      then
-         Elmt := First_Elmt (Op_List);
-         while Present (Elmt) loop
-            Subp := Node (Elmt);
+                  --  Create a reference to it
 
-            --  Literals are derived earlier in the process of building the
-            --  derived type, and are skipped here.
+                  Build_Itype_Reference (Acc_Type, Parent (Derived_Type));
 
-            if Ekind (Subp) = E_Enumeration_Literal then
-               null;
+               else
+                  Set_Etype (New_Id, Id_Type);
+               end if;
+            end;
 
-            --  The actual is a direct descendant and the common primitive
-            --  operations appear in the same order.
+         --  In Ada2012, a formal may have an incomplete type but the type
+         --  derivation that inherits the primitive follows the full view.
 
-            --  If the generic parent type is present, the derived type is an
-            --  instance of a formal derived type, and within the instance its
-            --  operations are those of the actual. We derive from the formal
-            --  type but make the inherited operations aliases of the
-            --  corresponding operations of the actual.
+         elsif Base_Type (Id_Type) = Base_Type (Parent_Type)
+           or else
+             (Ekind (Id_Type) = E_Record_Type_With_Private
+               and then Present (Full_View (Id_Type))
+               and then
+                 Base_Type (Full_View (Id_Type)) = Base_Type (Parent_Type))
+           or else
+             (Ada_Version >= Ada_2012
+               and then Ekind (Id_Type) = E_Incomplete_Type
+               and then Full_View (Id_Type) = Parent_Type)
+         then
+            --  Constraint checks on formals are generated during expansion,
+            --  based on the signature of the original subprogram. The bounds
+            --  of the derived type are not relevant, and thus we can use
+            --  the base type for the formals. However, the return type may be
+            --  used in a context that requires that the proper static bounds
+            --  be used (a case statement, for example)  and for those cases
+            --  we must use the derived type (first subtype), not its base.
 
-            else
-               pragma Assert (No (Node (Act_Elmt))
-                 or else (Primitive_Names_Match (Subp, Node (Act_Elmt))
-                           and then
-                             Type_Conformant
-                               (Subp, Node (Act_Elmt),
-                                Skip_Controlling_Formals => True)));
+            --  If the derived_type_definition has no constraints, we know that
+            --  the derived type has the same constraints as the first subtype
+            --  of the parent, and we can also use it rather than its base,
+            --  which can lead to more efficient code.
 
-               Derive_Subprogram
-                 (New_Subp, Subp, Derived_Type, Parent_Base, Node (Act_Elmt));
+            if Etype (Id) = Parent_Type then
+               if Is_Scalar_Type (Parent_Type)
+                 and then
+                   Subtypes_Statically_Compatible (Parent_Type, Derived_Type)
+               then
+                  Set_Etype (New_Id, Derived_Type);
 
-               if Present (Act_Elmt) then
-                  Next_Elmt (Act_Elmt);
+               elsif Nkind (Par) = N_Full_Type_Declaration
+                 and then
+                   Nkind (Type_Definition (Par)) = N_Derived_Type_Definition
+                 and then
+                   Is_Entity_Name
+                     (Subtype_Indication (Type_Definition (Par)))
+               then
+                  Set_Etype (New_Id, Derived_Type);
+
+               else
+                  Set_Etype (New_Id, Base_Type (Derived_Type));
                end if;
+
+            else
+               Set_Etype (New_Id, Base_Type (Derived_Type));
             end if;
 
-            Next_Elmt (Elmt);
-         end loop;
+         else
+            Set_Etype (New_Id, Etype (Id));
+         end if;
+      end Replace_Type;
 
-      --  Case 2: Derived_Type implements interfaces
+      ----------------------
+      -- Set_Derived_Name --
+      ----------------------
 
-      else
-         --  If the parent type has no predefined primitives we remove
-         --  predefined primitives from the list of primitives of generic
-         --  actual to simplify the complexity of this algorithm.
+      procedure Set_Derived_Name is
+         Nm : constant TSS_Name_Type := Get_TSS_Name (Parent_Subp);
+      begin
+         if Nm = TSS_Null then
+            Set_Chars (New_Subp, Chars (Parent_Subp));
+         else
+            Set_Chars (New_Subp, Make_TSS_Name (Base_Type (Derived_Type), Nm));
+         end if;
+      end Set_Derived_Name;
 
-         if Present (Generic_Actual) then
-            declare
-               Has_Predefined_Primitives : Boolean := False;
+   --  Start of processing for Derive_Subprogram
 
-            begin
-               --  Check if the parent type has predefined primitives
+   begin
+      New_Subp := New_Entity (Nkind (Parent_Subp), Sloc (Derived_Type));
+      Set_Ekind (New_Subp, Ekind (Parent_Subp));
 
-               Elmt := First_Elmt (Op_List);
-               while Present (Elmt) loop
-                  Subp := Node (Elmt);
+      --  Check whether the inherited subprogram is a private operation that
+      --  should be inherited but not yet made visible. Such subprograms can
+      --  become visible at a later point (e.g., the private part of a public
+      --  child unit) via Declare_Inherited_Private_Subprograms. If the
+      --  following predicate is true, then this is not such a private
+      --  operation and the subprogram simply inherits the name of the parent
+      --  subprogram. Note the special check for the names of controlled
+      --  operations, which are currently exempted from being inherited with
+      --  a hidden name because they must be findable for generation of
+      --  implicit run-time calls.
 
-                  if Is_Predefined_Dispatching_Operation (Subp)
-                    and then not Comes_From_Source (Ultimate_Alias (Subp))
-                  then
-                     Has_Predefined_Primitives := True;
-                     exit;
-                  end if;
+      if not Is_Hidden (Parent_Subp)
+        or else Is_Internal (Parent_Subp)
+        or else Is_Private_Overriding
+        or else Is_Internal_Name (Chars (Parent_Subp))
+        or else Nam_In (Chars (Parent_Subp), Name_Initialize,
+                                             Name_Adjust,
+                                             Name_Finalize)
+      then
+         Set_Derived_Name;
 
-                  Next_Elmt (Elmt);
-               end loop;
+      --  An inherited dispatching equality will be overridden by an internally
+      --  generated one, or by an explicit one, so preserve its name and thus
+      --  its entry in the dispatch table. Otherwise, if Parent_Subp is a
+      --  private operation it may become invisible if the full view has
+      --  progenitors, and the dispatch table will be malformed.
+      --  We check that the type is limited to handle the anomalous declaration
+      --  of Limited_Controlled, which is derived from a non-limited type, and
+      --  which is handled specially elsewhere as well.
 
-               --  Remove predefined primitives of Generic_Actual. We must use
-               --  an auxiliary list because in case of tagged types the value
-               --  returned by Collect_Primitive_Operations is the value stored
-               --  in its Primitive_Operations attribute (and we don't want to
-               --  modify its current contents).
+      elsif Chars (Parent_Subp) = Name_Op_Eq
+        and then Is_Dispatching_Operation (Parent_Subp)
+        and then Etype (Parent_Subp) = Standard_Boolean
+        and then not Is_Limited_Type (Etype (First_Formal (Parent_Subp)))
+        and then
+          Etype (First_Formal (Parent_Subp)) =
+            Etype (Next_Formal (First_Formal (Parent_Subp)))
+      then
+         Set_Derived_Name;
 
-               if not Has_Predefined_Primitives then
-                  declare
-                     Aux_List : constant Elist_Id := New_Elmt_List;
+      --  If parent is hidden, this can be a regular derivation if the
+      --  parent is immediately visible in a non-instantiating context,
+      --  or if we are in the private part of an instance. This test
+      --  should still be refined ???
 
-                  begin
-                     Elmt := First_Elmt (Act_List);
-                     while Present (Elmt) loop
-                        Subp := Node (Elmt);
+      --  The test for In_Instance_Not_Visible avoids inheriting the derived
+      --  operation as a non-visible operation in cases where the parent
+      --  subprogram might not be visible now, but was visible within the
+      --  original generic, so it would be wrong to make the inherited
+      --  subprogram non-visible now. (Not clear if this test is fully
+      --  correct; are there any cases where we should declare the inherited
+      --  operation as not visible to avoid it being overridden, e.g., when
+      --  the parent type is a generic actual with private primitives ???)
 
-                        if not Is_Predefined_Dispatching_Operation (Subp)
-                          or else Comes_From_Source (Subp)
-                        then
-                           Append_Elmt (Subp, Aux_List);
-                        end if;
+      --  (they should be treated the same as other private inherited
+      --  subprograms, but it's not clear how to do this cleanly). ???
 
-                        Next_Elmt (Elmt);
-                     end loop;
+      elsif (In_Open_Scopes (Scope (Base_Type (Parent_Type)))
+              and then Is_Immediately_Visible (Parent_Subp)
+              and then not In_Instance)
+        or else In_Instance_Not_Visible
+      then
+         Set_Derived_Name;
 
-                     Act_List := Aux_List;
-                  end;
-               end if;
+      --  Ada 2005 (AI-251): Regular derivation if the parent subprogram
+      --  overrides an interface primitive because interface primitives
+      --  must be visible in the partial view of the parent (RM 7.3 (7.3/2))
 
-               Act_Elmt := First_Elmt (Act_List);
-               Act_Subp := Node (Act_Elmt);
-            end;
-         end if;
+      elsif Ada_Version >= Ada_2005
+         and then Is_Dispatching_Operation (Parent_Subp)
+         and then Covers_Some_Interface (Parent_Subp)
+      then
+         Set_Derived_Name;
 
-         --  Stage 1: If the generic actual is not present we derive the
-         --  primitives inherited from the parent type. If the generic parent
-         --  type is present, the derived type is an instance of a formal
-         --  derived type, and within the instance its operations are those of
-         --  the actual. We derive from the formal type but make the inherited
-         --  operations aliases of the corresponding operations of the actual.
+      --  Otherwise, the type is inheriting a private operation, so enter
+      --  it with a special name so it can't be overridden.
 
-         Elmt := First_Elmt (Op_List);
-         while Present (Elmt) loop
-            Subp       := Node (Elmt);
-            Alias_Subp := Ultimate_Alias (Subp);
+      else
+         Set_Chars (New_Subp, New_External_Name (Chars (Parent_Subp), 'P'));
+      end if;
 
-            --  Do not derive internal entities of the parent that link
-            --  interface primitives with their covering primitive. These
-            --  entities will be added to this type when frozen.
+      Set_Parent (New_Subp, Parent (Derived_Type));
 
-            if Present (Interface_Alias (Subp)) then
-               goto Continue;
-            end if;
+      if Present (Actual_Subp) then
+         Replace_Type (Actual_Subp, New_Subp);
+      else
+         Replace_Type (Parent_Subp, New_Subp);
+      end if;
 
-            --  If the generic actual is present find the corresponding
-            --  operation in the generic actual. If the parent type is a
-            --  direct ancestor of the derived type then, even if it is an
-            --  interface, the operations are inherited from the primary
-            --  dispatch table and are in the proper order. If we detect here
-            --  that primitives are not in the same order we traverse the list
-            --  of primitive operations of the actual to find the one that
-            --  implements the interface primitive.
-
-            if Need_Search
-              or else
-                (Present (Generic_Actual)
-                  and then Present (Act_Subp)
-                  and then not
-                    (Primitive_Names_Match (Subp, Act_Subp)
-                       and then
-                     Type_Conformant (Subp, Act_Subp,
-                                      Skip_Controlling_Formals => True)))
-            then
-               pragma Assert (not Is_Ancestor (Parent_Base, Generic_Actual,
-                                               Use_Full_View => True));
+      Conditional_Delay (New_Subp, Parent_Subp);
 
-               --  Remember that we need searching for all pending primitives
+      --  If we are creating a renaming for a primitive operation of an
+      --  actual of a generic derived type, we must examine the signature
+      --  of the actual primitive, not that of the generic formal, which for
+      --  example may be an interface. However the name and initial value
+      --  of the inherited operation are those of the formal primitive.
 
-               Need_Search := True;
+      Formal := First_Formal (Parent_Subp);
 
-               --  Handle entities associated with interface primitives
+      if Present (Actual_Subp) then
+         Formal_Of_Actual := First_Formal (Actual_Subp);
+      else
+         Formal_Of_Actual := Empty;
+      end if;
 
-               if Present (Alias_Subp)
-                 and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
-                 and then not Is_Predefined_Dispatching_Operation (Subp)
-               then
-                  --  Search for the primitive in the homonym chain
+      while Present (Formal) loop
+         New_Formal := New_Copy (Formal);
 
-                  Act_Subp :=
-                    Find_Primitive_Covering_Interface
-                      (Tagged_Type => Generic_Actual,
-                       Iface_Prim  => Alias_Subp);
+         --  Normally we do not go copying parents, but in the case of
+         --  formals, we need to link up to the declaration (which is the
+         --  parameter specification), and it is fine to link up to the
+         --  original formal's parameter specification in this case.
 
-                  --  Previous search may not locate primitives covering
-                  --  interfaces defined in generics units or instantiations.
-                  --  (it fails if the covering primitive has formals whose
-                  --  type is also defined in generics or instantiations).
-                  --  In such case we search in the list of primitives of the
-                  --  generic actual for the internal entity that links the
-                  --  interface primitive and the covering primitive.
+         Set_Parent (New_Formal, Parent (Formal));
+         Append_Entity (New_Formal, New_Subp);
 
-                  if No (Act_Subp)
-                    and then Is_Generic_Type (Parent_Type)
-                  then
-                     --  This code has been designed to handle only generic
-                     --  formals that implement interfaces that are defined
-                     --  in a generic unit or instantiation. If this code is
-                     --  needed for other cases we must review it because
-                     --  (given that it relies on Original_Location to locate
-                     --  the primitive of Generic_Actual that covers the
-                     --  interface) it could leave linked through attribute
-                     --  Alias entities of unrelated instantiations).
+         if Present (Formal_Of_Actual) then
+            Replace_Type (Formal_Of_Actual, New_Formal);
+            Next_Formal (Formal_Of_Actual);
+         else
+            Replace_Type (Formal, New_Formal);
+         end if;
 
-                     pragma Assert
-                       (Is_Generic_Unit
-                          (Scope (Find_Dispatching_Type (Alias_Subp)))
-                         or else
-                           Instantiation_Depth
-                             (Sloc (Find_Dispatching_Type (Alias_Subp))) > 0);
+         Next_Formal (Formal);
+      end loop;
 
-                     declare
-                        Iface_Prim_Loc : constant Source_Ptr :=
-                                         Original_Location (Sloc (Alias_Subp));
+      --  If this derivation corresponds to a tagged generic actual, then
+      --  primitive operations rename those of the actual. Otherwise the
+      --  primitive operations rename those of the parent type, If the parent
+      --  renames an intrinsic operator, so does the new subprogram. We except
+      --  concatenation, which is always properly typed, and does not get
+      --  expanded as other intrinsic operations.
 
-                        Elmt : Elmt_Id;
-                        Prim : Entity_Id;
+      if No (Actual_Subp) then
+         if Is_Intrinsic_Subprogram (Parent_Subp) then
+            Set_Is_Intrinsic_Subprogram (New_Subp);
 
-                     begin
-                        Elmt :=
-                          First_Elmt (Primitive_Operations (Generic_Actual));
+            if Present (Alias (Parent_Subp))
+              and then Chars (Parent_Subp) /= Name_Op_Concat
+            then
+               Set_Alias (New_Subp, Alias (Parent_Subp));
+            else
+               Set_Alias (New_Subp, Parent_Subp);
+            end if;
 
-                        Search : while Present (Elmt) loop
-                           Prim := Node (Elmt);
+         else
+            Set_Alias (New_Subp, Parent_Subp);
+         end if;
 
-                           if Present (Interface_Alias (Prim))
-                             and then Original_Location
-                                        (Sloc (Interface_Alias (Prim))) =
-                                                              Iface_Prim_Loc
-                           then
-                              Act_Subp := Alias (Prim);
-                              exit Search;
-                           end if;
+      else
+         Set_Alias (New_Subp, Actual_Subp);
+      end if;
 
-                           Next_Elmt (Elmt);
-                        end loop Search;
-                     end;
-                  end if;
+      --  Inherit the "ghostness" from the parent subprogram
 
-                  pragma Assert (Present (Act_Subp)
-                    or else Is_Abstract_Type (Generic_Actual)
-                    or else Serious_Errors_Detected > 0);
+      if Is_Ghost_Entity (Alias (New_Subp)) then
+         Set_Is_Ghost_Entity (New_Subp);
+      end if;
 
-               --  Handle predefined primitives plus the rest of user-defined
-               --  primitives
+      --  Derived subprograms of a tagged type must inherit the convention
+      --  of the parent subprogram (a requirement of AI-117). Derived
+      --  subprograms of untagged types simply get convention Ada by default.
 
-               else
-                  Act_Elmt := First_Elmt (Act_List);
-                  while Present (Act_Elmt) loop
-                     Act_Subp := Node (Act_Elmt);
+      --  If the derived type is a tagged generic formal type with unknown
+      --  discriminants, its convention is intrinsic (RM 6.3.1 (8)).
 
-                     exit when Primitive_Names_Match (Subp, Act_Subp)
-                       and then Type_Conformant
-                                  (Subp, Act_Subp,
-                                   Skip_Controlling_Formals => True)
-                       and then No (Interface_Alias (Act_Subp));
+      --  However, if the type is derived from a generic formal, the further
+      --  inherited subprogram has the convention of the non-generic ancestor.
+      --  Otherwise there would be no way to override the operation.
+      --  (This is subject to forthcoming ARG discussions).
 
-                     Next_Elmt (Act_Elmt);
-                  end loop;
+      if Is_Tagged_Type (Derived_Type) then
+         if Is_Generic_Type (Derived_Type)
+           and then Has_Unknown_Discriminants (Derived_Type)
+         then
+            Set_Convention (New_Subp, Convention_Intrinsic);
 
-                  if No (Act_Elmt) then
-                     Act_Subp := Empty;
-                  end if;
-               end if;
+         else
+            if Is_Generic_Type (Parent_Type)
+              and then Has_Unknown_Discriminants (Parent_Type)
+            then
+               Set_Convention (New_Subp, Convention (Alias (Parent_Subp)));
+            else
+               Set_Convention (New_Subp, Convention (Parent_Subp));
             end if;
+         end if;
+      end if;
 
-            --   Case 1: If the parent is a limited interface then it has the
-            --   predefined primitives of synchronized interfaces. However, the
-            --   actual type may be a non-limited type and hence it does not
-            --   have such primitives.
+      --  Predefined controlled operations retain their name even if the parent
+      --  is hidden (see above), but they are not primitive operations if the
+      --  ancestor is not visible, for example if the parent is a private
+      --  extension completed with a controlled extension. Note that a full
+      --  type that is controlled can break privacy: the flag Is_Controlled is
+      --  set on both views of the type.
 
-            if Present (Generic_Actual)
-              and then not Present (Act_Subp)
-              and then Is_Limited_Interface (Parent_Base)
-              and then Is_Predefined_Interface_Primitive (Subp)
-            then
-               null;
+      if Is_Controlled (Parent_Type)
+        and then Nam_In (Chars (Parent_Subp), Name_Initialize,
+                                              Name_Adjust,
+                                              Name_Finalize)
+        and then Is_Hidden (Parent_Subp)
+        and then not Is_Visibly_Controlled (Parent_Type)
+      then
+         Set_Is_Hidden (New_Subp);
+      end if;
 
-            --  Case 2: Inherit entities associated with interfaces that were
-            --  not covered by the parent type. We exclude here null interface
-            --  primitives because they do not need special management.
+      Set_Is_Imported (New_Subp, Is_Imported (Parent_Subp));
+      Set_Is_Exported (New_Subp, Is_Exported (Parent_Subp));
 
-            --  We also exclude interface operations that are renamings. If the
-            --  subprogram is an explicit renaming of an interface primitive,
-            --  it is a regular primitive operation, and the presence of its
-            --  alias is not relevant: it has to be derived like any other
-            --  primitive.
+      if Ekind (Parent_Subp) = E_Procedure then
+         Set_Is_Valued_Procedure
+           (New_Subp, Is_Valued_Procedure (Parent_Subp));
+      else
+         Set_Has_Controlling_Result
+           (New_Subp, Has_Controlling_Result (Parent_Subp));
+      end if;
 
-            elsif Present (Alias (Subp))
-              and then Nkind (Unit_Declaration_Node (Subp)) /=
-                                            N_Subprogram_Renaming_Declaration
-              and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
-              and then not
-                (Nkind (Parent (Alias_Subp)) = N_Procedure_Specification
-                  and then Null_Present (Parent (Alias_Subp)))
-            then
-               --  If this is an abstract private type then we transfer the
-               --  derivation of the interface primitive from the partial view
-               --  to the full view. This is safe because all the interfaces
-               --  must be visible in the partial view. Done to avoid adding
-               --  a new interface derivation to the private part of the
-               --  enclosing package; otherwise this new derivation would be
-               --  decorated as hidden when the analysis of the enclosing
-               --  package completes.
+      --  No_Return must be inherited properly. If this is overridden in the
+      --  case of a dispatching operation, then a check is made in Sem_Disp
+      --  that the overriding operation is also No_Return (no such check is
+      --  required for the case of non-dispatching operation.
 
-               if Is_Abstract_Type (Derived_Type)
-                 and then In_Private_Part (Current_Scope)
-                 and then Has_Private_Declaration (Derived_Type)
-               then
-                  declare
-                     Partial_View : Entity_Id;
-                     Elmt         : Elmt_Id;
-                     Ent          : Entity_Id;
+      Set_No_Return (New_Subp, No_Return (Parent_Subp));
 
-                  begin
-                     Partial_View := First_Entity (Current_Scope);
-                     loop
-                        exit when No (Partial_View)
-                          or else (Has_Private_Declaration (Partial_View)
-                                     and then
-                                   Full_View (Partial_View) = Derived_Type);
+      --  A derived function with a controlling result is abstract. If the
+      --  Derived_Type is a nonabstract formal generic derived type, then
+      --  inherited operations are not abstract: the required check is done at
+      --  instantiation time. If the derivation is for a generic actual, the
+      --  function is not abstract unless the actual is.
 
-                        Next_Entity (Partial_View);
-                     end loop;
+      if Is_Generic_Type (Derived_Type)
+        and then not Is_Abstract_Type (Derived_Type)
+      then
+         null;
 
-                     --  If the partial view was not found then the source code
-                     --  has errors and the derivation is not needed.
+      --  Ada 2005 (AI-228): Calculate the "require overriding" and "abstract"
+      --  properties of the subprogram, as defined in RM-3.9.3(4/2-6/2).
 
-                     if Present (Partial_View) then
-                        Elmt :=
-                          First_Elmt (Primitive_Operations (Partial_View));
-                        while Present (Elmt) loop
-                           Ent := Node (Elmt);
+      --  A subprogram subject to pragma Extensions_Visible with value False
+      --  requires overriding if the subprogram has at least one controlling
+      --  OUT parameter (SPARK RM 6.1.7(6)).
 
-                           if Present (Alias (Ent))
-                             and then Ultimate_Alias (Ent) = Alias (Subp)
-                           then
-                              Append_Elmt
-                                (Ent, Primitive_Operations (Derived_Type));
-                              exit;
-                           end if;
+      elsif Ada_Version >= Ada_2005
+        and then (Is_Abstract_Subprogram (Alias (New_Subp))
+                   or else (Is_Tagged_Type (Derived_Type)
+                             and then Etype (New_Subp) = Derived_Type
+                             and then not Is_Null_Extension (Derived_Type))
+                   or else (Is_Tagged_Type (Derived_Type)
+                             and then Ekind (Etype (New_Subp)) =
+                                                       E_Anonymous_Access_Type
+                             and then Designated_Type (Etype (New_Subp)) =
+                                                        Derived_Type
+                             and then not Is_Null_Extension (Derived_Type))
+                   or else (Comes_From_Source (Alias (New_Subp))
+                             and then Is_EVF_Procedure (Alias (New_Subp))))
+        and then No (Actual_Subp)
+      then
+         if not Is_Tagged_Type (Derived_Type)
+           or else Is_Abstract_Type (Derived_Type)
+           or else Is_Abstract_Subprogram (Alias (New_Subp))
+         then
+            Set_Is_Abstract_Subprogram (New_Subp);
+         else
+            Set_Requires_Overriding (New_Subp);
+         end if;
 
-                           Next_Elmt (Elmt);
-                        end loop;
+      elsif Ada_Version < Ada_2005
+        and then (Is_Abstract_Subprogram (Alias (New_Subp))
+                   or else (Is_Tagged_Type (Derived_Type)
+                             and then Etype (New_Subp) = Derived_Type
+                             and then No (Actual_Subp)))
+      then
+         Set_Is_Abstract_Subprogram (New_Subp);
 
-                        --  If the interface primitive was not found in the
-                        --  partial view then this interface primitive was
-                        --  overridden. We add a derivation to activate in
-                        --  Derive_Progenitor_Subprograms the machinery to
-                        --  search for it.
+      --  AI05-0097 : an inherited operation that dispatches on result is
+      --  abstract if the derived type is abstract, even if the parent type
+      --  is concrete and the derived type is a null extension.
 
-                        if No (Elmt) then
-                           Derive_Interface_Subprogram
-                             (New_Subp    => New_Subp,
-                              Subp        => Subp,
-                              Actual_Subp => Act_Subp);
-                        end if;
-                     end if;
-                  end;
-               else
-                  Derive_Interface_Subprogram
-                    (New_Subp     => New_Subp,
-                     Subp         => Subp,
-                     Actual_Subp  => Act_Subp);
-               end if;
+      elsif Has_Controlling_Result (Alias (New_Subp))
+        and then Is_Abstract_Type (Etype (New_Subp))
+      then
+         Set_Is_Abstract_Subprogram (New_Subp);
 
-            --  Case 3: Common derivation
+      --  Finally, if the parent type is abstract we must verify that all
+      --  inherited operations are either non-abstract or overridden, or that
+      --  the derived type itself is abstract (this check is performed at the
+      --  end of a package declaration, in Check_Abstract_Overriding). A
+      --  private overriding in the parent type will not be visible in the
+      --  derivation if we are not in an inner package or in a child unit of
+      --  the parent type, in which case the abstractness of the inherited
+      --  operation is carried to the new subprogram.
 
-            else
-               Derive_Subprogram
-                 (New_Subp     => New_Subp,
-                  Parent_Subp  => Subp,
-                  Derived_Type => Derived_Type,
-                  Parent_Type  => Parent_Base,
-                  Actual_Subp  => Act_Subp);
-            end if;
+      elsif Is_Abstract_Type (Parent_Type)
+        and then not In_Open_Scopes (Scope (Parent_Type))
+        and then Is_Private_Overriding
+        and then Is_Abstract_Subprogram (Visible_Subp)
+      then
+         if No (Actual_Subp) then
+            Set_Alias (New_Subp, Visible_Subp);
+            Set_Is_Abstract_Subprogram (New_Subp, True);
 
-            --  No need to update Act_Elm if we must search for the
-            --  corresponding operation in the generic actual
+         else
+            --  If this is a derivation for an instance of a formal derived
+            --  type, abstractness comes from the primitive operation of the
+            --  actual, not from the operation inherited from the ancestor.
 
-            if not Need_Search
-              and then Present (Act_Elmt)
-            then
-               Next_Elmt (Act_Elmt);
-               Act_Subp := Node (Act_Elmt);
-            end if;
+            Set_Is_Abstract_Subprogram
+              (New_Subp, Is_Abstract_Subprogram (Actual_Subp));
+         end if;
+      end if;
 
-            <<Continue>>
-            Next_Elmt (Elmt);
-         end loop;
+      New_Overloaded_Entity (New_Subp, Derived_Type);
 
-         --  Inherit additional operations from progenitors. If the derived
-         --  type is a generic actual, there are not new primitive operations
-         --  for the type because it has those of the actual, and therefore
-         --  nothing needs to be done. The renamings generated above are not
-         --  primitive operations, and their purpose is simply to make the
-         --  proper operations visible within an instantiation.
+      --  Check for case of a derived subprogram for the instantiation of a
+      --  formal derived tagged type, if so mark the subprogram as dispatching
+      --  and inherit the dispatching attributes of the actual subprogram. The
+      --  derived subprogram is effectively renaming of the actual subprogram,
+      --  so it needs to have the same attributes as the actual.
 
-         if No (Generic_Actual) then
-            Derive_Progenitor_Subprograms (Parent_Base, Derived_Type);
+      if Present (Actual_Subp)
+        and then Is_Dispatching_Operation (Actual_Subp)
+      then
+         Set_Is_Dispatching_Operation (New_Subp);
+
+         if Present (DTC_Entity (Actual_Subp)) then
+            Set_DTC_Entity (New_Subp, DTC_Entity (Actual_Subp));
+            Set_DT_Position_Value (New_Subp, DT_Position (Actual_Subp));
          end if;
       end if;
 
-      --  Final check: Direct descendants must have their primitives in the
-      --  same order. We exclude from this test untagged types and instances
-      --  of formal derived types. We skip this test if we have already
-      --  reported serious errors in the sources.
-
-      pragma Assert (not Is_Tagged_Type (Derived_Type)
-        or else Present (Generic_Actual)
-        or else Serious_Errors_Detected > 0
-        or else Check_Derived_Type);
-   end Derive_Subprograms;
+      --  Indicate that a derived subprogram does not require a body and that
+      --  it does not require processing of default expressions.
 
-   --------------------------------
-   -- Derived_Standard_Character --
-   --------------------------------
+      Set_Has_Completion (New_Subp);
+      Set_Default_Expressions_Processed (New_Subp);
 
-   procedure Derived_Standard_Character
-     (N            : Node_Id;
-      Parent_Type  : Entity_Id;
-      Derived_Type : Entity_Id)
-   is
-      Loc           : constant Source_Ptr := Sloc (N);
-      Def           : constant Node_Id    := Type_Definition (N);
-      Indic         : constant Node_Id    := Subtype_Indication (Def);
-      Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
-      Implicit_Base : constant Entity_Id  :=
-                        Create_Itype
-                          (E_Enumeration_Type, N, Derived_Type, 'B');
+      if Ekind (New_Subp) = E_Function then
+         Set_Mechanism (New_Subp, Mechanism (Parent_Subp));
+      end if;
+   end Derive_Subprogram;
 
-      Lo : Node_Id;
-      Hi : Node_Id;
+   ------------------------
+   -- Derive_Subprograms --
+   ------------------------
 
-   begin
-      Discard_Node (Process_Subtype (Indic, N));
+   procedure Derive_Subprograms
+     (Parent_Type    : Entity_Id;
+      Derived_Type   : Entity_Id;
+      Generic_Actual : Entity_Id := Empty)
+   is
+      Op_List : constant Elist_Id :=
+                  Collect_Primitive_Operations (Parent_Type);
 
-      Set_Etype     (Implicit_Base, Parent_Base);
-      Set_Size_Info (Implicit_Base, Root_Type (Parent_Type));
-      Set_RM_Size   (Implicit_Base, RM_Size (Root_Type (Parent_Type)));
+      function Check_Derived_Type return Boolean;
+      --  Check that all the entities derived from Parent_Type are found in
+      --  the list of primitives of Derived_Type exactly in the same order.
 
-      Set_Is_Character_Type  (Implicit_Base, True);
-      Set_Has_Delayed_Freeze (Implicit_Base);
+      procedure Derive_Interface_Subprogram
+        (New_Subp    : in out Entity_Id;
+         Subp        : Entity_Id;
+         Actual_Subp : Entity_Id);
+      --  Derive New_Subp from the ultimate alias of the parent subprogram Subp
+      --  (which is an interface primitive). If Generic_Actual is present then
+      --  Actual_Subp is the actual subprogram corresponding with the generic
+      --  subprogram Subp.
 
-      --  The bounds of the implicit base are the bounds of the parent base.
-      --  Note that their type is the parent base.
+      function Check_Derived_Type return Boolean is
+         E        : Entity_Id;
+         Elmt     : Elmt_Id;
+         List     : Elist_Id;
+         New_Subp : Entity_Id;
+         Op_Elmt  : Elmt_Id;
+         Subp     : Entity_Id;
 
-      Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
-      Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
+      begin
+         --  Traverse list of entities in the current scope searching for
+         --  an incomplete type whose full-view is derived type
 
-      Set_Scalar_Range (Implicit_Base,
-        Make_Range (Loc,
-          Low_Bound  => Lo,
-          High_Bound => Hi));
+         E := First_Entity (Scope (Derived_Type));
+         while Present (E) and then E /= Derived_Type loop
+            if Ekind (E) = E_Incomplete_Type
+              and then Present (Full_View (E))
+              and then Full_View (E) = Derived_Type
+            then
+               --  Disable this test if Derived_Type completes an incomplete
+               --  type because in such case more primitives can be added
+               --  later to the list of primitives of Derived_Type by routine
+               --  Process_Incomplete_Dependents
 
-      Conditional_Delay (Derived_Type, Parent_Type);
+               return True;
+            end if;
 
-      Set_Ekind (Derived_Type, E_Enumeration_Subtype);
-      Set_Etype (Derived_Type, Implicit_Base);
-      Set_Size_Info         (Derived_Type, Parent_Type);
+            E := Next_Entity (E);
+         end loop;
 
-      if Unknown_RM_Size (Derived_Type) then
-         Set_RM_Size (Derived_Type, RM_Size (Parent_Type));
-      end if;
+         List := Collect_Primitive_Operations (Derived_Type);
+         Elmt := First_Elmt (List);
 
-      Set_Is_Character_Type (Derived_Type, True);
+         Op_Elmt := First_Elmt (Op_List);
+         while Present (Op_Elmt) loop
+            Subp     := Node (Op_Elmt);
+            New_Subp := Node (Elmt);
 
-      if Nkind (Indic) /= N_Subtype_Indication then
+            --  At this early stage Derived_Type has no entities with attribute
+            --  Interface_Alias. In addition, such primitives are always
+            --  located at the end of the list of primitives of Parent_Type.
+            --  Therefore, if found we can safely stop processing pending
+            --  entities.
 
-         --  If no explicit constraint, the bounds are those
-         --  of the parent type.
+            exit when Present (Interface_Alias (Subp));
 
-         Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Type));
-         Hi := New_Copy_Tree (Type_High_Bound (Parent_Type));
-         Set_Scalar_Range (Derived_Type, Make_Range (Loc, Lo, Hi));
-      end if;
+            --  Handle hidden entities
 
-      Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
+            if not Is_Predefined_Dispatching_Operation (Subp)
+              and then Is_Hidden (Subp)
+            then
+               if Present (New_Subp)
+                 and then Primitive_Names_Match (Subp, New_Subp)
+               then
+                  Next_Elmt (Elmt);
+               end if;
 
-      --  Because the implicit base is used in the conversion of the bounds, we
-      --  have to freeze it now. This is similar to what is done for numeric
-      --  types, and it equally suspicious, but otherwise a non-static bound
-      --  will have a reference to an unfrozen type, which is rejected by Gigi
-      --  (???). This requires specific care for definition of stream
-      --  attributes. For details, see comments at the end of
-      --  Build_Derived_Numeric_Type.
+            else
+               if not Present (New_Subp)
+                 or else Ekind (Subp) /= Ekind (New_Subp)
+                 or else not Primitive_Names_Match (Subp, New_Subp)
+               then
+                  return False;
+               end if;
 
-      Freeze_Before (N, Implicit_Base);
-   end Derived_Standard_Character;
+               Next_Elmt (Elmt);
+            end if;
 
-   ------------------------------
-   -- Derived_Type_Declaration --
-   ------------------------------
+            Next_Elmt (Op_Elmt);
+         end loop;
 
-   procedure Derived_Type_Declaration
-     (T             : Entity_Id;
-      N             : Node_Id;
-      Is_Completion : Boolean)
-   is
-      Parent_Type  : Entity_Id;
+         return True;
+      end Check_Derived_Type;
 
-      function Comes_From_Generic (Typ : Entity_Id) return Boolean;
-      --  Check whether the parent type is a generic formal, or derives
-      --  directly or indirectly from one.
+      ---------------------------------
+      -- Derive_Interface_Subprogram --
+      ---------------------------------
 
-      ------------------------
-      -- Comes_From_Generic --
-      ------------------------
+      procedure Derive_Interface_Subprogram
+        (New_Subp    : in out Entity_Id;
+         Subp        : Entity_Id;
+         Actual_Subp : Entity_Id)
+      is
+         Iface_Subp : constant Entity_Id := Ultimate_Alias (Subp);
+         Iface_Type : constant Entity_Id := Find_Dispatching_Type (Iface_Subp);
 
-      function Comes_From_Generic (Typ : Entity_Id) return Boolean is
       begin
-         if Is_Generic_Type (Typ) then
-            return True;
+         pragma Assert (Is_Interface (Iface_Type));
 
-         elsif Is_Generic_Type (Root_Type (Parent_Type)) then
-            return True;
+         Derive_Subprogram
+           (New_Subp     => New_Subp,
+            Parent_Subp  => Iface_Subp,
+            Derived_Type => Derived_Type,
+            Parent_Type  => Iface_Type,
+            Actual_Subp  => Actual_Subp);
 
-         elsif Is_Private_Type (Typ)
-           and then Present (Full_View (Typ))
-           and then Is_Generic_Type (Root_Type (Full_View (Typ)))
-         then
-            return True;
+         --  Given that this new interface entity corresponds with a primitive
+         --  of the parent that was not overridden we must leave it associated
+         --  with its parent primitive to ensure that it will share the same
+         --  dispatch table slot when overridden.
 
-         elsif Is_Generic_Actual_Type (Typ) then
-            return True;
+         if No (Actual_Subp) then
+            Set_Alias (New_Subp, Subp);
+
+         --  For instantiations this is not needed since the previous call to
+         --  Derive_Subprogram leaves the entity well decorated.
 
          else
-            return False;
+            pragma Assert (Alias (New_Subp) = Actual_Subp);
+            null;
          end if;
-      end Comes_From_Generic;
+      end Derive_Interface_Subprogram;
 
       --  Local variables
 
-      Def          : constant Node_Id := Type_Definition (N);
-      Iface_Def    : Node_Id;
-      Indic        : constant Node_Id := Subtype_Indication (Def);
-      Extension    : constant Node_Id := Record_Extension_Part (Def);
-      Parent_Node  : Node_Id;
-      Taggd        : Boolean;
+      Alias_Subp   : Entity_Id;
+      Act_List     : Elist_Id;
+      Act_Elmt     : Elmt_Id;
+      Act_Subp     : Entity_Id := Empty;
+      Elmt         : Elmt_Id;
+      Need_Search  : Boolean   := False;
+      New_Subp     : Entity_Id := Empty;
+      Parent_Base  : Entity_Id;
+      Subp         : Entity_Id;
 
-   --  Start of processing for Derived_Type_Declaration
+   --  Start of processing for Derive_Subprograms
 
    begin
-      Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
-
-      --  Ada 2005 (AI-251): In case of interface derivation check that the
-      --  parent is also an interface.
-
-      if Interface_Present (Def) then
-         Check_SPARK_Restriction ("interface is not allowed", Def);
-
-         if not Is_Interface (Parent_Type) then
-            Diagnose_Interface (Indic, Parent_Type);
-
-         else
-            Parent_Node := Parent (Base_Type (Parent_Type));
-            Iface_Def   := Type_Definition (Parent_Node);
+      if Ekind (Parent_Type) = E_Record_Type_With_Private
+        and then Has_Discriminants (Parent_Type)
+        and then Present (Full_View (Parent_Type))
+      then
+         Parent_Base := Full_View (Parent_Type);
+      else
+         Parent_Base := Parent_Type;
+      end if;
 
-            --  Ada 2005 (AI-251): Limited interfaces can only inherit from
-            --  other limited interfaces.
+      if Present (Generic_Actual) then
+         Act_List := Collect_Primitive_Operations (Generic_Actual);
+         Act_Elmt := First_Elmt (Act_List);
+      else
+         Act_List := No_Elist;
+         Act_Elmt := No_Elmt;
+      end if;
 
-            if Limited_Present (Def) then
-               if Limited_Present (Iface_Def) then
-                  null;
+      --  Derive primitives inherited from the parent. Note that if the generic
+      --  actual is present, this is not really a type derivation, it is a
+      --  completion within an instance.
 
-               elsif Protected_Present (Iface_Def) then
-                  Error_Msg_NE
-                    ("descendant of& must be declared"
-                       & " as a protected interface",
-                         N, Parent_Type);
+      --  Case 1: Derived_Type does not implement interfaces
 
-               elsif Synchronized_Present (Iface_Def) then
-                  Error_Msg_NE
-                    ("descendant of& must be declared"
-                       & " as a synchronized interface",
-                         N, Parent_Type);
+      if not Is_Tagged_Type (Derived_Type)
+        or else (not Has_Interfaces (Derived_Type)
+                  and then not (Present (Generic_Actual)
+                                 and then Has_Interfaces (Generic_Actual)))
+      then
+         Elmt := First_Elmt (Op_List);
+         while Present (Elmt) loop
+            Subp := Node (Elmt);
 
-               elsif Task_Present (Iface_Def) then
-                  Error_Msg_NE
-                    ("descendant of& must be declared as a task interface",
-                       N, Parent_Type);
+            --  Literals are derived earlier in the process of building the
+            --  derived type, and are skipped here.
 
-               else
-                  Error_Msg_N
-                    ("(Ada 2005) limited interface cannot "
-                     & "inherit from non-limited interface", Indic);
-               end if;
+            if Ekind (Subp) = E_Enumeration_Literal then
+               null;
 
-            --  Ada 2005 (AI-345): Non-limited interfaces can only inherit
-            --  from non-limited or limited interfaces.
+            --  The actual is a direct descendant and the common primitive
+            --  operations appear in the same order.
 
-            elsif not Protected_Present (Def)
-              and then not Synchronized_Present (Def)
-              and then not Task_Present (Def)
-            then
-               if Limited_Present (Iface_Def) then
-                  null;
+            --  If the generic parent type is present, the derived type is an
+            --  instance of a formal derived type, and within the instance its
+            --  operations are those of the actual. We derive from the formal
+            --  type but make the inherited operations aliases of the
+            --  corresponding operations of the actual.
 
-               elsif Protected_Present (Iface_Def) then
-                  Error_Msg_NE
-                    ("descendant of& must be declared"
-                       & " as a protected interface",
-                         N, Parent_Type);
+            else
+               pragma Assert (No (Node (Act_Elmt))
+                 or else (Primitive_Names_Match (Subp, Node (Act_Elmt))
+                           and then
+                             Type_Conformant
+                               (Subp, Node (Act_Elmt),
+                                Skip_Controlling_Formals => True)));
 
-               elsif Synchronized_Present (Iface_Def) then
-                  Error_Msg_NE
-                    ("descendant of& must be declared"
-                       & " as a synchronized interface",
-                         N, Parent_Type);
+               Derive_Subprogram
+                 (New_Subp, Subp, Derived_Type, Parent_Base, Node (Act_Elmt));
 
-               elsif Task_Present (Iface_Def) then
-                  Error_Msg_NE
-                    ("descendant of& must be declared as a task interface",
-                       N, Parent_Type);
-               else
-                  null;
+               if Present (Act_Elmt) then
+                  Next_Elmt (Act_Elmt);
                end if;
             end if;
-         end if;
-      end if;
-
-      if Is_Tagged_Type (Parent_Type)
-        and then Is_Concurrent_Type (Parent_Type)
-        and then not Is_Interface (Parent_Type)
-      then
-         Error_Msg_N
-           ("parent type of a record extension cannot be "
-            & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
-         Set_Etype (T, Any_Type);
-         return;
-      end if;
-
-      --  Ada 2005 (AI-251): Decorate all the names in the list of ancestor
-      --  interfaces
 
-      if Is_Tagged_Type (Parent_Type)
-        and then Is_Non_Empty_List (Interface_List (Def))
-      then
-         declare
-            Intf : Node_Id;
-            T    : Entity_Id;
-
-         begin
-            Intf := First (Interface_List (Def));
-            while Present (Intf) loop
-               T := Find_Type_Of_Subtype_Indic (Intf);
-
-               if not Is_Interface (T) then
-                  Diagnose_Interface (Intf, T);
+            Next_Elmt (Elmt);
+         end loop;
 
-               --  Check the rules of 3.9.4(12/2) and 7.5(2/2) that disallow
-               --  a limited type from having a nonlimited progenitor.
+      --  Case 2: Derived_Type implements interfaces
 
-               elsif (Limited_Present (Def)
-                       or else (not Is_Interface (Parent_Type)
-                                 and then Is_Limited_Type (Parent_Type)))
-                 and then not Is_Limited_Interface (T)
-               then
-                  Error_Msg_NE
-                   ("progenitor interface& of limited type must be limited",
-                     N, T);
-               end if;
+      else
+         --  If the parent type has no predefined primitives we remove
+         --  predefined primitives from the list of primitives of generic
+         --  actual to simplify the complexity of this algorithm.
 
-               Next (Intf);
-            end loop;
-         end;
-      end if;
+         if Present (Generic_Actual) then
+            declare
+               Has_Predefined_Primitives : Boolean := False;
 
-      if Parent_Type = Any_Type
-        or else Etype (Parent_Type) = Any_Type
-        or else (Is_Class_Wide_Type (Parent_Type)
-                  and then Etype (Parent_Type) = T)
-      then
-         --  If Parent_Type is undefined or illegal, make new type into a
-         --  subtype of Any_Type, and set a few attributes to prevent cascaded
-         --  errors. If this is a self-definition, emit error now.
+            begin
+               --  Check if the parent type has predefined primitives
 
-         if T = Parent_Type
-           or else T = Etype (Parent_Type)
-         then
-            Error_Msg_N ("type cannot be used in its own definition", Indic);
-         end if;
+               Elmt := First_Elmt (Op_List);
+               while Present (Elmt) loop
+                  Subp := Node (Elmt);
 
-         Set_Ekind        (T, Ekind (Parent_Type));
-         Set_Etype        (T, Any_Type);
-         Set_Scalar_Range (T, Scalar_Range (Any_Type));
+                  if Is_Predefined_Dispatching_Operation (Subp)
+                    and then not Comes_From_Source (Ultimate_Alias (Subp))
+                  then
+                     Has_Predefined_Primitives := True;
+                     exit;
+                  end if;
 
-         if Is_Tagged_Type (T)
-           and then Is_Record_Type (T)
-         then
-            Set_Direct_Primitive_Operations (T, New_Elmt_List);
-         end if;
+                  Next_Elmt (Elmt);
+               end loop;
 
-         return;
-      end if;
+               --  Remove predefined primitives of Generic_Actual. We must use
+               --  an auxiliary list because in case of tagged types the value
+               --  returned by Collect_Primitive_Operations is the value stored
+               --  in its Primitive_Operations attribute (and we don't want to
+               --  modify its current contents).
 
-      --  Ada 2005 (AI-251): The case in which the parent of the full-view is
-      --  an interface is special because the list of interfaces in the full
-      --  view can be given in any order. For example:
+               if not Has_Predefined_Primitives then
+                  declare
+                     Aux_List : constant Elist_Id := New_Elmt_List;
 
-      --     type A is interface;
-      --     type B is interface and A;
-      --     type D is new B with private;
-      --   private
-      --     type D is new A and B with null record; -- 1 --
+                  begin
+                     Elmt := First_Elmt (Act_List);
+                     while Present (Elmt) loop
+                        Subp := Node (Elmt);
 
-      --  In this case we perform the following transformation of -1-:
+                        if not Is_Predefined_Dispatching_Operation (Subp)
+                          or else Comes_From_Source (Subp)
+                        then
+                           Append_Elmt (Subp, Aux_List);
+                        end if;
 
-      --     type D is new B and A with null record;
+                        Next_Elmt (Elmt);
+                     end loop;
 
-      --  If the parent of the full-view covers the parent of the partial-view
-      --  we have two possible cases:
+                     Act_List := Aux_List;
+                  end;
+               end if;
 
-      --     1) They have the same parent
-      --     2) The parent of the full-view implements some further interfaces
+               Act_Elmt := First_Elmt (Act_List);
+               Act_Subp := Node (Act_Elmt);
+            end;
+         end if;
 
-      --  In both cases we do not need to perform the transformation. In the
-      --  first case the source program is correct and the transformation is
-      --  not needed; in the second case the source program does not fulfill
-      --  the no-hidden interfaces rule (AI-396) and the error will be reported
-      --  later.
+         --  Stage 1: If the generic actual is not present we derive the
+         --  primitives inherited from the parent type. If the generic parent
+         --  type is present, the derived type is an instance of a formal
+         --  derived type, and within the instance its operations are those of
+         --  the actual. We derive from the formal type but make the inherited
+         --  operations aliases of the corresponding operations of the actual.
 
-      --  This transformation not only simplifies the rest of the analysis of
-      --  this type declaration but also simplifies the correct generation of
-      --  the object layout to the expander.
+         Elmt := First_Elmt (Op_List);
+         while Present (Elmt) loop
+            Subp       := Node (Elmt);
+            Alias_Subp := Ultimate_Alias (Subp);
 
-      if In_Private_Part (Current_Scope)
-        and then Is_Interface (Parent_Type)
-      then
-         declare
-            Iface               : Node_Id;
-            Partial_View        : Entity_Id;
-            Partial_View_Parent : Entity_Id;
-            New_Iface           : Node_Id;
+            --  Do not derive internal entities of the parent that link
+            --  interface primitives with their covering primitive. These
+            --  entities will be added to this type when frozen.
 
-         begin
-            --  Look for the associated private type declaration
+            if Present (Interface_Alias (Subp)) then
+               goto Continue;
+            end if;
 
-            Partial_View := First_Entity (Current_Scope);
-            loop
-               exit when No (Partial_View)
-                 or else (Has_Private_Declaration (Partial_View)
-                           and then Full_View (Partial_View) = T);
+            --  If the generic actual is present find the corresponding
+            --  operation in the generic actual. If the parent type is a
+            --  direct ancestor of the derived type then, even if it is an
+            --  interface, the operations are inherited from the primary
+            --  dispatch table and are in the proper order. If we detect here
+            --  that primitives are not in the same order we traverse the list
+            --  of primitive operations of the actual to find the one that
+            --  implements the interface primitive.
 
-               Next_Entity (Partial_View);
-            end loop;
+            if Need_Search
+              or else
+                (Present (Generic_Actual)
+                  and then Present (Act_Subp)
+                  and then not
+                    (Primitive_Names_Match (Subp, Act_Subp)
+                       and then
+                     Type_Conformant (Subp, Act_Subp,
+                                      Skip_Controlling_Formals => True)))
+            then
+               pragma Assert (not Is_Ancestor (Parent_Base, Generic_Actual,
+                                               Use_Full_View => True));
 
-            --  If the partial view was not found then the source code has
-            --  errors and the transformation is not needed.
+               --  Remember that we need searching for all pending primitives
 
-            if Present (Partial_View) then
-               Partial_View_Parent := Etype (Partial_View);
+               Need_Search := True;
 
-               --  If the parent of the full-view covers the parent of the
-               --  partial-view we have nothing else to do.
+               --  Handle entities associated with interface primitives
 
-               if Interface_Present_In_Ancestor
-                    (Parent_Type, Partial_View_Parent)
+               if Present (Alias_Subp)
+                 and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
+                 and then not Is_Predefined_Dispatching_Operation (Subp)
                then
-                  null;
+                  --  Search for the primitive in the homonym chain
 
-               --  Traverse the list of interfaces of the full-view to look
-               --  for the parent of the partial-view and perform the tree
-               --  transformation.
+                  Act_Subp :=
+                    Find_Primitive_Covering_Interface
+                      (Tagged_Type => Generic_Actual,
+                       Iface_Prim  => Alias_Subp);
 
-               else
-                  Iface := First (Interface_List (Def));
-                  while Present (Iface) loop
-                     if Etype (Iface) = Etype (Partial_View) then
-                        Rewrite (Subtype_Indication (Def),
-                          New_Copy (Subtype_Indication
-                                     (Parent (Partial_View))));
+                  --  Previous search may not locate primitives covering
+                  --  interfaces defined in generics units or instantiations.
+                  --  (it fails if the covering primitive has formals whose
+                  --  type is also defined in generics or instantiations).
+                  --  In such case we search in the list of primitives of the
+                  --  generic actual for the internal entity that links the
+                  --  interface primitive and the covering primitive.
 
-                        New_Iface :=
-                          Make_Identifier (Sloc (N), Chars (Parent_Type));
-                        Append (New_Iface, Interface_List (Def));
+                  if No (Act_Subp)
+                    and then Is_Generic_Type (Parent_Type)
+                  then
+                     --  This code has been designed to handle only generic
+                     --  formals that implement interfaces that are defined
+                     --  in a generic unit or instantiation. If this code is
+                     --  needed for other cases we must review it because
+                     --  (given that it relies on Original_Location to locate
+                     --  the primitive of Generic_Actual that covers the
+                     --  interface) it could leave linked through attribute
+                     --  Alias entities of unrelated instantiations).
 
-                        --  Analyze the transformed code
+                     pragma Assert
+                       (Is_Generic_Unit
+                          (Scope (Find_Dispatching_Type (Alias_Subp)))
+                         or else
+                           Instantiation_Depth
+                             (Sloc (Find_Dispatching_Type (Alias_Subp))) > 0);
 
-                        Derived_Type_Declaration (T, N, Is_Completion);
-                        return;
-                     end if;
+                     declare
+                        Iface_Prim_Loc : constant Source_Ptr :=
+                                         Original_Location (Sloc (Alias_Subp));
 
-                     Next (Iface);
-                  end loop;
-               end if;
-            end if;
-         end;
-      end if;
+                        Elmt : Elmt_Id;
+                        Prim : Entity_Id;
 
-      --  Only composite types other than array types are allowed to have
-      --  discriminants. In SPARK, no types are allowed to have discriminants.
+                     begin
+                        Elmt :=
+                          First_Elmt (Primitive_Operations (Generic_Actual));
 
-      if Present (Discriminant_Specifications (N)) then
-         if (Is_Elementary_Type (Parent_Type)
-              or else Is_Array_Type (Parent_Type))
-           and then not Error_Posted (N)
-         then
-            Error_Msg_N
-              ("elementary or array type cannot have discriminants",
-               Defining_Identifier (First (Discriminant_Specifications (N))));
-            Set_Has_Discriminants (T, False);
-         else
-            Check_SPARK_Restriction ("discriminant type is not allowed", N);
-         end if;
-      end if;
+                        Search : while Present (Elmt) loop
+                           Prim := Node (Elmt);
+
+                           if Present (Interface_Alias (Prim))
+                             and then Original_Location
+                                        (Sloc (Interface_Alias (Prim))) =
+                                                              Iface_Prim_Loc
+                           then
+                              Act_Subp := Alias (Prim);
+                              exit Search;
+                           end if;
 
-      --  In Ada 83, a derived type defined in a package specification cannot
-      --  be used for further derivation until the end of its visible part.
-      --  Note that derivation in the private part of the package is allowed.
+                           Next_Elmt (Elmt);
+                        end loop Search;
+                     end;
+                  end if;
 
-      if Ada_Version = Ada_83
-        and then Is_Derived_Type (Parent_Type)
-        and then In_Visible_Part (Scope (Parent_Type))
-      then
-         if Ada_Version = Ada_83 and then Comes_From_Source (Indic) then
-            Error_Msg_N
-              ("(Ada 83): premature use of type for derivation", Indic);
-         end if;
-      end if;
+                  pragma Assert (Present (Act_Subp)
+                    or else Is_Abstract_Type (Generic_Actual)
+                    or else Serious_Errors_Detected > 0);
 
-      --  Check for early use of incomplete or private type
+               --  Handle predefined primitives plus the rest of user-defined
+               --  primitives
 
-      if Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
-         Error_Msg_N ("premature derivation of incomplete type", Indic);
-         return;
+               else
+                  Act_Elmt := First_Elmt (Act_List);
+                  while Present (Act_Elmt) loop
+                     Act_Subp := Node (Act_Elmt);
 
-      elsif (Is_Incomplete_Or_Private_Type (Parent_Type)
-              and then not Comes_From_Generic (Parent_Type))
-        or else Has_Private_Component (Parent_Type)
-      then
-         --  The ancestor type of a formal type can be incomplete, in which
-         --  case only the operations of the partial view are available in the
-         --  generic. Subsequent checks may be required when the full view is
-         --  analyzed to verify that a derivation from a tagged type has an
-         --  extension.
+                     exit when Primitive_Names_Match (Subp, Act_Subp)
+                       and then Type_Conformant
+                                  (Subp, Act_Subp,
+                                   Skip_Controlling_Formals => True)
+                       and then No (Interface_Alias (Act_Subp));
 
-         if Nkind (Original_Node (N)) = N_Formal_Type_Declaration then
-            null;
+                     Next_Elmt (Act_Elmt);
+                  end loop;
 
-         elsif No (Underlying_Type (Parent_Type))
-           or else Has_Private_Component (Parent_Type)
-         then
-            Error_Msg_N
-              ("premature derivation of derived or private type", Indic);
+                  if No (Act_Elmt) then
+                     Act_Subp := Empty;
+                  end if;
+               end if;
+            end if;
 
-            --  Flag the type itself as being in error, this prevents some
-            --  nasty problems with subsequent uses of the malformed type.
+            --   Case 1: If the parent is a limited interface then it has the
+            --   predefined primitives of synchronized interfaces. However, the
+            --   actual type may be a non-limited type and hence it does not
+            --   have such primitives.
 
-            Set_Error_Posted (T);
+            if Present (Generic_Actual)
+              and then not Present (Act_Subp)
+              and then Is_Limited_Interface (Parent_Base)
+              and then Is_Predefined_Interface_Primitive (Subp)
+            then
+               null;
 
-         --  Check that within the immediate scope of an untagged partial
-         --  view it's illegal to derive from the partial view if the
-         --  full view is tagged. (7.3(7))
+            --  Case 2: Inherit entities associated with interfaces that were
+            --  not covered by the parent type. We exclude here null interface
+            --  primitives because they do not need special management.
 
-         --  We verify that the Parent_Type is a partial view by checking
-         --  that it is not a Full_Type_Declaration (i.e. a private type or
-         --  private extension declaration), to distinguish a partial view
-         --  from  a derivation from a private type which also appears as
-         --  E_Private_Type. If the parent base type is not declared in an
-         --  enclosing scope there is no need to check.
+            --  We also exclude interface operations that are renamings. If the
+            --  subprogram is an explicit renaming of an interface primitive,
+            --  it is a regular primitive operation, and the presence of its
+            --  alias is not relevant: it has to be derived like any other
+            --  primitive.
 
-         elsif Present (Full_View (Parent_Type))
-           and then Nkind (Parent (Parent_Type)) /= N_Full_Type_Declaration
-           and then not Is_Tagged_Type (Parent_Type)
-           and then Is_Tagged_Type (Full_View (Parent_Type))
-           and then In_Open_Scopes (Scope (Base_Type (Parent_Type)))
-         then
-            Error_Msg_N
-              ("premature derivation from type with tagged full view",
-                Indic);
-         end if;
-      end if;
+            elsif Present (Alias (Subp))
+              and then Nkind (Unit_Declaration_Node (Subp)) /=
+                                            N_Subprogram_Renaming_Declaration
+              and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
+              and then not
+                (Nkind (Parent (Alias_Subp)) = N_Procedure_Specification
+                  and then Null_Present (Parent (Alias_Subp)))
+            then
+               --  If this is an abstract private type then we transfer the
+               --  derivation of the interface primitive from the partial view
+               --  to the full view. This is safe because all the interfaces
+               --  must be visible in the partial view. Done to avoid adding
+               --  a new interface derivation to the private part of the
+               --  enclosing package; otherwise this new derivation would be
+               --  decorated as hidden when the analysis of the enclosing
+               --  package completes.
 
-      --  Check that form of derivation is appropriate
+               if Is_Abstract_Type (Derived_Type)
+                 and then In_Private_Part (Current_Scope)
+                 and then Has_Private_Declaration (Derived_Type)
+               then
+                  declare
+                     Partial_View : Entity_Id;
+                     Elmt         : Elmt_Id;
+                     Ent          : Entity_Id;
 
-      Taggd := Is_Tagged_Type (Parent_Type);
+                  begin
+                     Partial_View := First_Entity (Current_Scope);
+                     loop
+                        exit when No (Partial_View)
+                          or else (Has_Private_Declaration (Partial_View)
+                                    and then
+                                      Full_View (Partial_View) = Derived_Type);
 
-      --  Perhaps the parent type should be changed to the class-wide type's
-      --  specific type in this case to prevent cascading errors ???
+                        Next_Entity (Partial_View);
+                     end loop;
 
-      if Present (Extension) and then Is_Class_Wide_Type (Parent_Type) then
-         Error_Msg_N ("parent type must not be a class-wide type", Indic);
-         return;
-      end if;
+                     --  If the partial view was not found then the source code
+                     --  has errors and the derivation is not needed.
 
-      if Present (Extension) and then not Taggd then
-         Error_Msg_N
-           ("type derived from untagged type cannot have extension", Indic);
+                     if Present (Partial_View) then
+                        Elmt :=
+                          First_Elmt (Primitive_Operations (Partial_View));
+                        while Present (Elmt) loop
+                           Ent := Node (Elmt);
 
-      elsif No (Extension) and then Taggd then
+                           if Present (Alias (Ent))
+                             and then Ultimate_Alias (Ent) = Alias (Subp)
+                           then
+                              Append_Elmt
+                                (Ent, Primitive_Operations (Derived_Type));
+                              exit;
+                           end if;
 
-         --  If this declaration is within a private part (or body) of a
-         --  generic instantiation then the derivation is allowed (the parent
-         --  type can only appear tagged in this case if it's a generic actual
-         --  type, since it would otherwise have been rejected in the analysis
-         --  of the generic template).
+                           Next_Elmt (Elmt);
+                        end loop;
 
-         if not Is_Generic_Actual_Type (Parent_Type)
-           or else In_Visible_Part (Scope (Parent_Type))
-         then
-            if Is_Class_Wide_Type (Parent_Type) then
-               Error_Msg_N
-                 ("parent type must not be a class-wide type", Indic);
+                        --  If the interface primitive was not found in the
+                        --  partial view then this interface primitive was
+                        --  overridden. We add a derivation to activate in
+                        --  Derive_Progenitor_Subprograms the machinery to
+                        --  search for it.
 
-               --  Use specific type to prevent cascaded errors.
+                        if No (Elmt) then
+                           Derive_Interface_Subprogram
+                             (New_Subp    => New_Subp,
+                              Subp        => Subp,
+                              Actual_Subp => Act_Subp);
+                        end if;
+                     end if;
+                  end;
+               else
+                  Derive_Interface_Subprogram
+                    (New_Subp     => New_Subp,
+                     Subp         => Subp,
+                     Actual_Subp  => Act_Subp);
+               end if;
 
-               Parent_Type := Etype (Parent_Type);
+            --  Case 3: Common derivation
 
             else
-               Error_Msg_N
-                 ("type derived from tagged type must have extension", Indic);
+               Derive_Subprogram
+                 (New_Subp     => New_Subp,
+                  Parent_Subp  => Subp,
+                  Derived_Type => Derived_Type,
+                  Parent_Type  => Parent_Base,
+                  Actual_Subp  => Act_Subp);
+            end if;
+
+            --  No need to update Act_Elm if we must search for the
+            --  corresponding operation in the generic actual
+
+            if not Need_Search
+              and then Present (Act_Elmt)
+            then
+               Next_Elmt (Act_Elmt);
+               Act_Subp := Node (Act_Elmt);
             end if;
+
+            <<Continue>>
+            Next_Elmt (Elmt);
+         end loop;
+
+         --  Inherit additional operations from progenitors. If the derived
+         --  type is a generic actual, there are not new primitive operations
+         --  for the type because it has those of the actual, and therefore
+         --  nothing needs to be done. The renamings generated above are not
+         --  primitive operations, and their purpose is simply to make the
+         --  proper operations visible within an instantiation.
+
+         if No (Generic_Actual) then
+            Derive_Progenitor_Subprograms (Parent_Base, Derived_Type);
          end if;
       end if;
 
-      --  AI-443: Synchronized formal derived types require a private
-      --  extension. There is no point in checking the ancestor type or
-      --  the progenitors since the construct is wrong to begin with.
+      --  Final check: Direct descendants must have their primitives in the
+      --  same order. We exclude from this test untagged types and instances
+      --  of formal derived types. We skip this test if we have already
+      --  reported serious errors in the sources.
 
-      if Ada_Version >= Ada_2005
-        and then Is_Generic_Type (T)
-        and then Present (Original_Node (N))
-      then
-         declare
-            Decl : constant Node_Id := Original_Node (N);
+      pragma Assert (not Is_Tagged_Type (Derived_Type)
+        or else Present (Generic_Actual)
+        or else Serious_Errors_Detected > 0
+        or else Check_Derived_Type);
+   end Derive_Subprograms;
+
+   --------------------------------
+   -- Derived_Standard_Character --
+   --------------------------------
+
+   procedure Derived_Standard_Character
+     (N            : Node_Id;
+      Parent_Type  : Entity_Id;
+      Derived_Type : Entity_Id)
+   is
+      Loc           : constant Source_Ptr := Sloc (N);
+      Def           : constant Node_Id    := Type_Definition (N);
+      Indic         : constant Node_Id    := Subtype_Indication (Def);
+      Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
+      Implicit_Base : constant Entity_Id  :=
+                        Create_Itype
+                          (E_Enumeration_Type, N, Derived_Type, 'B');
 
-         begin
-            if Nkind (Decl) = N_Formal_Type_Declaration
-              and then Nkind (Formal_Type_Definition (Decl)) =
-                         N_Formal_Derived_Type_Definition
-              and then Synchronized_Present (Formal_Type_Definition (Decl))
-              and then No (Extension)
+      Lo : Node_Id;
+      Hi : Node_Id;
 
-               --  Avoid emitting a duplicate error message
+   begin
+      Discard_Node (Process_Subtype (Indic, N));
 
-              and then not Error_Posted (Indic)
-            then
-               Error_Msg_N
-                 ("synchronized derived type must have extension", N);
-            end if;
-         end;
-      end if;
+      Set_Etype     (Implicit_Base, Parent_Base);
+      Set_Size_Info (Implicit_Base, Root_Type (Parent_Type));
+      Set_RM_Size   (Implicit_Base, RM_Size (Root_Type (Parent_Type)));
 
-      if Null_Exclusion_Present (Def)
-        and then not Is_Access_Type (Parent_Type)
-      then
-         Error_Msg_N ("null exclusion can only apply to an access type", N);
-      end if;
+      Set_Is_Character_Type  (Implicit_Base, True);
+      Set_Has_Delayed_Freeze (Implicit_Base);
 
-      --  Avoid deriving parent primitives of underlying record views
+      --  The bounds of the implicit base are the bounds of the parent base.
+      --  Note that their type is the parent base.
 
-      Build_Derived_Type (N, Parent_Type, T, Is_Completion,
-        Derive_Subps => not Is_Underlying_Record_View (T));
+      Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
+      Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
 
-      --  AI-419: The parent type of an explicitly limited derived type must
-      --  be a limited type or a limited interface.
+      Set_Scalar_Range (Implicit_Base,
+        Make_Range (Loc,
+          Low_Bound  => Lo,
+          High_Bound => Hi));
 
-      if Limited_Present (Def) then
-         Set_Is_Limited_Record (T);
+      Conditional_Delay (Derived_Type, Parent_Type);
 
-         if Is_Interface (T) then
-            Set_Is_Limited_Interface (T);
-         end if;
+      Set_Ekind (Derived_Type, E_Enumeration_Subtype);
+      Set_Etype (Derived_Type, Implicit_Base);
+      Set_Size_Info         (Derived_Type, Parent_Type);
 
-         if not Is_Limited_Type (Parent_Type)
-           and then
-             (not Is_Interface (Parent_Type)
-               or else not Is_Limited_Interface (Parent_Type))
-         then
-            --  AI05-0096: a derivation in the private part of an instance is
-            --  legal if the generic formal is untagged limited, and the actual
-            --  is non-limited.
+      if Unknown_RM_Size (Derived_Type) then
+         Set_RM_Size (Derived_Type, RM_Size (Parent_Type));
+      end if;
 
-            if Is_Generic_Actual_Type (Parent_Type)
-              and then In_Private_Part (Current_Scope)
-              and then
-                not Is_Tagged_Type
-                      (Generic_Parent_Type (Parent (Parent_Type)))
-            then
-               null;
+      Set_Is_Character_Type (Derived_Type, True);
 
-            else
-               Error_Msg_NE
-                 ("parent type& of limited type must be limited",
-                  N, Parent_Type);
-            end if;
-         end if;
-      end if;
+      if Nkind (Indic) /= N_Subtype_Indication then
 
-      --  In SPARK, there are no derived type definitions other than type
-      --  extensions of tagged record types.
+         --  If no explicit constraint, the bounds are those
+         --  of the parent type.
 
-      if No (Extension) then
-         Check_SPARK_Restriction
-           ("derived type is not allowed", Original_Node (N));
+         Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Type));
+         Hi := New_Copy_Tree (Type_High_Bound (Parent_Type));
+         Set_Scalar_Range (Derived_Type, Make_Range (Loc, Lo, Hi));
       end if;
-   end Derived_Type_Declaration;
 
-   ------------------------
-   -- Diagnose_Interface --
-   ------------------------
+      Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
 
-   procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id) is
-   begin
-      if not Is_Interface (E)
-        and then  E /= Any_Type
-      then
-         Error_Msg_NE ("(Ada 2005) & must be an interface", N, E);
-      end if;
-   end Diagnose_Interface;
+      --  Because the implicit base is used in the conversion of the bounds, we
+      --  have to freeze it now. This is similar to what is done for numeric
+      --  types, and it equally suspicious, but otherwise a non-static bound
+      --  will have a reference to an unfrozen type, which is rejected by Gigi
+      --  (???). This requires specific care for definition of stream
+      --  attributes. For details, see comments at the end of
+      --  Build_Derived_Numeric_Type.
 
-   ----------------------------------
-   -- Enumeration_Type_Declaration --
-   ----------------------------------
+      Freeze_Before (N, Implicit_Base);
+   end Derived_Standard_Character;
 
-   procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id) is
-      Ev     : Uint;
-      L      : Node_Id;
-      R_Node : Node_Id;
-      B_Node : Node_Id;
+   ------------------------------
+   -- Derived_Type_Declaration --
+   ------------------------------
 
-   begin
-      --  Create identifier node representing lower bound
+   procedure Derived_Type_Declaration
+     (T             : Entity_Id;
+      N             : Node_Id;
+      Is_Completion : Boolean)
+   is
+      Parent_Type  : Entity_Id;
 
-      B_Node := New_Node (N_Identifier, Sloc (Def));
-      L := First (Literals (Def));
-      Set_Chars (B_Node, Chars (L));
-      Set_Entity (B_Node,  L);
-      Set_Etype (B_Node, T);
-      Set_Is_Static_Expression (B_Node, True);
+      function Comes_From_Generic (Typ : Entity_Id) return Boolean;
+      --  Check whether the parent type is a generic formal, or derives
+      --  directly or indirectly from one.
 
-      R_Node := New_Node (N_Range, Sloc (Def));
-      Set_Low_Bound  (R_Node, B_Node);
+      ------------------------
+      -- Comes_From_Generic --
+      ------------------------
 
-      Set_Ekind (T, E_Enumeration_Type);
-      Set_First_Literal (T, L);
-      Set_Etype (T, T);
-      Set_Is_Constrained (T);
+      function Comes_From_Generic (Typ : Entity_Id) return Boolean is
+      begin
+         if Is_Generic_Type (Typ) then
+            return True;
 
-      Ev := Uint_0;
+         elsif Is_Generic_Type (Root_Type (Parent_Type)) then
+            return True;
 
-      --  Loop through literals of enumeration type setting pos and rep values
-      --  except that if the Ekind is already set, then it means the literal
-      --  was already constructed (case of a derived type declaration and we
-      --  should not disturb the Pos and Rep values.
+         elsif Is_Private_Type (Typ)
+           and then Present (Full_View (Typ))
+           and then Is_Generic_Type (Root_Type (Full_View (Typ)))
+         then
+            return True;
 
-      while Present (L) loop
-         if Ekind (L) /= E_Enumeration_Literal then
-            Set_Ekind (L, E_Enumeration_Literal);
-            Set_Enumeration_Pos (L, Ev);
-            Set_Enumeration_Rep (L, Ev);
-            Set_Is_Known_Valid  (L, True);
+         elsif Is_Generic_Actual_Type (Typ) then
+            return True;
+
+         else
+            return False;
          end if;
+      end Comes_From_Generic;
 
-         Set_Etype (L, T);
-         New_Overloaded_Entity (L);
-         Generate_Definition (L);
-         Set_Convention (L, Convention_Intrinsic);
+      --  Local variables
 
-         --  Case of character literal
+      Def          : constant Node_Id := Type_Definition (N);
+      Iface_Def    : Node_Id;
+      Indic        : constant Node_Id := Subtype_Indication (Def);
+      Extension    : constant Node_Id := Record_Extension_Part (Def);
+      Parent_Node  : Node_Id;
+      Taggd        : Boolean;
 
-         if Nkind (L) = N_Defining_Character_Literal then
-            Set_Is_Character_Type (T, True);
+   --  Start of processing for Derived_Type_Declaration
 
-            --  Check violation of No_Wide_Characters
+   begin
+      Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
 
-            if Restriction_Check_Required (No_Wide_Characters) then
-               Get_Name_String (Chars (L));
+      --  Ada 2005 (AI-251): In case of interface derivation check that the
+      --  parent is also an interface.
 
-               if Name_Len >= 3 and then Name_Buffer (1 .. 2) = "QW" then
-                  Check_Restriction (No_Wide_Characters, L);
-               end if;
-            end if;
-         end if;
+      if Interface_Present (Def) then
+         Check_SPARK_05_Restriction ("interface is not allowed", Def);
 
-         Ev := Ev + 1;
-         Next (L);
-      end loop;
+         if not Is_Interface (Parent_Type) then
+            Diagnose_Interface (Indic, Parent_Type);
 
-      --  Now create a node representing upper bound
+         else
+            Parent_Node := Parent (Base_Type (Parent_Type));
+            Iface_Def   := Type_Definition (Parent_Node);
 
-      B_Node := New_Node (N_Identifier, Sloc (Def));
-      Set_Chars (B_Node, Chars (Last (Literals (Def))));
-      Set_Entity (B_Node,  Last (Literals (Def)));
-      Set_Etype (B_Node, T);
-      Set_Is_Static_Expression (B_Node, True);
+            --  Ada 2005 (AI-251): Limited interfaces can only inherit from
+            --  other limited interfaces.
 
-      Set_High_Bound (R_Node, B_Node);
+            if Limited_Present (Def) then
+               if Limited_Present (Iface_Def) then
+                  null;
 
-      --  Initialize various fields of the type. Some of this information
-      --  may be overwritten later through rep.clauses.
+               elsif Protected_Present (Iface_Def) then
+                  Error_Msg_NE
+                    ("descendant of& must be declared"
+                       & " as a protected interface",
+                         N, Parent_Type);
 
-      Set_Scalar_Range    (T, R_Node);
-      Set_RM_Size         (T, UI_From_Int (Minimum_Size (T)));
-      Set_Enum_Esize      (T);
-      Set_Enum_Pos_To_Rep (T, Empty);
+               elsif Synchronized_Present (Iface_Def) then
+                  Error_Msg_NE
+                    ("descendant of& must be declared"
+                       & " as a synchronized interface",
+                         N, Parent_Type);
+
+               elsif Task_Present (Iface_Def) then
+                  Error_Msg_NE
+                    ("descendant of& must be declared as a task interface",
+                       N, Parent_Type);
+
+               else
+                  Error_Msg_N
+                    ("(Ada 2005) limited interface cannot "
+                     & "inherit from non-limited interface", Indic);
+               end if;
+
+            --  Ada 2005 (AI-345): Non-limited interfaces can only inherit
+            --  from non-limited or limited interfaces.
+
+            elsif not Protected_Present (Def)
+              and then not Synchronized_Present (Def)
+              and then not Task_Present (Def)
+            then
+               if Limited_Present (Iface_Def) then
+                  null;
 
-      --  Set Discard_Names if configuration pragma set, or if there is
-      --  a parameterless pragma in the current declarative region
+               elsif Protected_Present (Iface_Def) then
+                  Error_Msg_NE
+                    ("descendant of& must be declared"
+                       & " as a protected interface",
+                         N, Parent_Type);
 
-      if Global_Discard_Names or else Discard_Names (Scope (T)) then
-         Set_Discard_Names (T);
-      end if;
+               elsif Synchronized_Present (Iface_Def) then
+                  Error_Msg_NE
+                    ("descendant of& must be declared"
+                       & " as a synchronized interface",
+                         N, Parent_Type);
 
-      --  Process end label if there is one
+               elsif Task_Present (Iface_Def) then
+                  Error_Msg_NE
+                    ("descendant of& must be declared as a task interface",
+                       N, Parent_Type);
+               else
+                  null;
+               end if;
+            end if;
+         end if;
+      end if;
 
-      if Present (Def) then
-         Process_End_Label (Def, 'e', T);
+      if Is_Tagged_Type (Parent_Type)
+        and then Is_Concurrent_Type (Parent_Type)
+        and then not Is_Interface (Parent_Type)
+      then
+         Error_Msg_N
+           ("parent type of a record extension cannot be "
+            & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
+         Set_Etype (T, Any_Type);
+         return;
       end if;
-   end Enumeration_Type_Declaration;
 
-   ---------------------------------
-   -- Expand_To_Stored_Constraint --
-   ---------------------------------
+      --  Ada 2005 (AI-251): Decorate all the names in the list of ancestor
+      --  interfaces
 
-   function Expand_To_Stored_Constraint
-     (Typ        : Entity_Id;
-      Constraint : Elist_Id) return Elist_Id
-   is
-      Explicitly_Discriminated_Type : Entity_Id;
-      Expansion    : Elist_Id;
-      Discriminant : Entity_Id;
+      if Is_Tagged_Type (Parent_Type)
+        and then Is_Non_Empty_List (Interface_List (Def))
+      then
+         declare
+            Intf : Node_Id;
+            T    : Entity_Id;
 
-      function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id;
-      --  Find the nearest type that actually specifies discriminants
+         begin
+            Intf := First (Interface_List (Def));
+            while Present (Intf) loop
+               T := Find_Type_Of_Subtype_Indic (Intf);
 
-      ---------------------------------
-      -- Type_With_Explicit_Discrims --
-      ---------------------------------
+               if not Is_Interface (T) then
+                  Diagnose_Interface (Intf, T);
 
-      function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id is
-         Typ : constant E := Base_Type (Id);
+               --  Check the rules of 3.9.4(12/2) and 7.5(2/2) that disallow
+               --  a limited type from having a nonlimited progenitor.
 
-      begin
-         if Ekind (Typ) in Incomplete_Or_Private_Kind then
-            if Present (Full_View (Typ)) then
-               return Type_With_Explicit_Discrims (Full_View (Typ));
-            end if;
+               elsif (Limited_Present (Def)
+                       or else (not Is_Interface (Parent_Type)
+                                 and then Is_Limited_Type (Parent_Type)))
+                 and then not Is_Limited_Interface (T)
+               then
+                  Error_Msg_NE
+                   ("progenitor interface& of limited type must be limited",
+                     N, T);
+               end if;
 
-         else
-            if Has_Discriminants (Typ) then
-               return Typ;
-            end if;
-         end if;
+               Next (Intf);
+            end loop;
+         end;
+      end if;
 
-         if Etype (Typ) = Typ then
-            return Empty;
-         elsif Has_Discriminants (Typ) then
-            return Typ;
-         else
-            return Type_With_Explicit_Discrims (Etype (Typ));
+      if Parent_Type = Any_Type
+        or else Etype (Parent_Type) = Any_Type
+        or else (Is_Class_Wide_Type (Parent_Type)
+                  and then Etype (Parent_Type) = T)
+      then
+         --  If Parent_Type is undefined or illegal, make new type into a
+         --  subtype of Any_Type, and set a few attributes to prevent cascaded
+         --  errors. If this is a self-definition, emit error now.
+
+         if T = Parent_Type or else T = Etype (Parent_Type) then
+            Error_Msg_N ("type cannot be used in its own definition", Indic);
          end if;
 
-      end Type_With_Explicit_Discrims;
+         Set_Ekind        (T, Ekind (Parent_Type));
+         Set_Etype        (T, Any_Type);
+         Set_Scalar_Range (T, Scalar_Range (Any_Type));
 
-   --  Start of processing for Expand_To_Stored_Constraint
+         if Is_Tagged_Type (T)
+           and then Is_Record_Type (T)
+         then
+            Set_Direct_Primitive_Operations (T, New_Elmt_List);
+         end if;
 
-   begin
-      if No (Constraint)
-        or else Is_Empty_Elmt_List (Constraint)
-      then
-         return No_Elist;
+         return;
       end if;
 
-      Explicitly_Discriminated_Type := Type_With_Explicit_Discrims (Typ);
+      --  Ada 2005 (AI-251): The case in which the parent of the full-view is
+      --  an interface is special because the list of interfaces in the full
+      --  view can be given in any order. For example:
 
-      if No (Explicitly_Discriminated_Type) then
-         return No_Elist;
-      end if;
+      --     type A is interface;
+      --     type B is interface and A;
+      --     type D is new B with private;
+      --   private
+      --     type D is new A and B with null record; -- 1 --
 
-      Expansion := New_Elmt_List;
+      --  In this case we perform the following transformation of -1-:
 
-      Discriminant :=
-         First_Stored_Discriminant (Explicitly_Discriminated_Type);
-      while Present (Discriminant) loop
-         Append_Elmt
-           (Get_Discriminant_Value
-              (Discriminant, Explicitly_Discriminated_Type, Constraint),
-            To => Expansion);
-         Next_Stored_Discriminant (Discriminant);
-      end loop;
+      --     type D is new B and A with null record;
 
-      return Expansion;
-   end Expand_To_Stored_Constraint;
+      --  If the parent of the full-view covers the parent of the partial-view
+      --  we have two possible cases:
 
-   ---------------------------
-   -- Find_Hidden_Interface --
-   ---------------------------
+      --     1) They have the same parent
+      --     2) The parent of the full-view implements some further interfaces
 
-   function Find_Hidden_Interface
-     (Src  : Elist_Id;
-      Dest : Elist_Id) return Entity_Id
-   is
-      Iface      : Entity_Id;
-      Iface_Elmt : Elmt_Id;
+      --  In both cases we do not need to perform the transformation. In the
+      --  first case the source program is correct and the transformation is
+      --  not needed; in the second case the source program does not fulfill
+      --  the no-hidden interfaces rule (AI-396) and the error will be reported
+      --  later.
 
-   begin
-      if Present (Src) and then Present (Dest) then
-         Iface_Elmt := First_Elmt (Src);
-         while Present (Iface_Elmt) loop
-            Iface := Node (Iface_Elmt);
+      --  This transformation not only simplifies the rest of the analysis of
+      --  this type declaration but also simplifies the correct generation of
+      --  the object layout to the expander.
 
-            if Is_Interface (Iface)
-              and then not Contain_Interface (Iface, Dest)
-            then
-               return Iface;
-            end if;
+      if In_Private_Part (Current_Scope)
+        and then Is_Interface (Parent_Type)
+      then
+         declare
+            Iface               : Node_Id;
+            Partial_View        : Entity_Id;
+            Partial_View_Parent : Entity_Id;
+            New_Iface           : Node_Id;
 
-            Next_Elmt (Iface_Elmt);
-         end loop;
-      end if;
+         begin
+            --  Look for the associated private type declaration
 
-      return Empty;
-   end Find_Hidden_Interface;
+            Partial_View := First_Entity (Current_Scope);
+            loop
+               exit when No (Partial_View)
+                 or else (Has_Private_Declaration (Partial_View)
+                           and then Full_View (Partial_View) = T);
 
-   --------------------
-   -- Find_Type_Name --
-   --------------------
+               Next_Entity (Partial_View);
+            end loop;
 
-   function Find_Type_Name (N : Node_Id) return Entity_Id is
-      Id       : constant Entity_Id := Defining_Identifier (N);
-      Prev     : Entity_Id;
-      New_Id   : Entity_Id;
-      Prev_Par : Node_Id;
+            --  If the partial view was not found then the source code has
+            --  errors and the transformation is not needed.
 
-      procedure Check_Duplicate_Aspects;
-      --  Check that aspects specified in a completion have not been specified
-      --  already in the partial view. Type_Invariant and others can be
-      --  specified on either view but never on both.
+            if Present (Partial_View) then
+               Partial_View_Parent := Etype (Partial_View);
 
-      procedure Tag_Mismatch;
-      --  Diagnose a tagged partial view whose full view is untagged.
-      --  We post the message on the full view, with a reference to
-      --  the previous partial view. The partial view can be private
-      --  or incomplete, and these are handled in a different manner,
-      --  so we determine the position of the error message from the
-      --  respective slocs of both.
+               --  If the parent of the full-view covers the parent of the
+               --  partial-view we have nothing else to do.
 
-      -----------------------------
-      -- Check_Duplicate_Aspects --
-      -----------------------------
-      procedure Check_Duplicate_Aspects is
-         Prev_Aspects   : constant List_Id := Aspect_Specifications (Prev_Par);
-         Full_Aspects   : constant List_Id := Aspect_Specifications (N);
-         F_Spec, P_Spec : Node_Id;
+               if Interface_Present_In_Ancestor
+                    (Parent_Type, Partial_View_Parent)
+               then
+                  null;
 
-      begin
-         if Present (Prev_Aspects) and then Present (Full_Aspects) then
-            F_Spec := First (Full_Aspects);
-            while Present (F_Spec) loop
-               P_Spec := First (Prev_Aspects);
-               while Present (P_Spec) loop
-                  if
-                    Chars (Identifier (P_Spec)) = Chars (Identifier (F_Spec))
-                  then
-                     Error_Msg_N
-                       ("aspect already specified in private declaration",
-                         F_Spec);
-                     Remove (F_Spec);
-                     return;
-                  end if;
+               --  Traverse the list of interfaces of the full-view to look
+               --  for the parent of the partial-view and perform the tree
+               --  transformation.
+
+               else
+                  Iface := First (Interface_List (Def));
+                  while Present (Iface) loop
+                     if Etype (Iface) = Etype (Partial_View) then
+                        Rewrite (Subtype_Indication (Def),
+                          New_Copy (Subtype_Indication
+                                     (Parent (Partial_View))));
 
-                  Next (P_Spec);
-               end loop;
+                        New_Iface :=
+                          Make_Identifier (Sloc (N), Chars (Parent_Type));
+                        Append (New_Iface, Interface_List (Def));
 
-               Next (F_Spec);
-            end loop;
-         end if;
-      end Check_Duplicate_Aspects;
+                        --  Analyze the transformed code
 
-      ------------------
-      -- Tag_Mismatch --
-      ------------------
+                        Derived_Type_Declaration (T, N, Is_Completion);
+                        return;
+                     end if;
 
-      procedure Tag_Mismatch is
-      begin
-         if Sloc (Prev) < Sloc (Id) then
-            if Ada_Version >= Ada_2012
-              and then Nkind (N) = N_Private_Type_Declaration
-            then
-               Error_Msg_NE
-                 ("declaration of private } must be a tagged type ", Id, Prev);
-            else
-               Error_Msg_NE
-                 ("full declaration of } must be a tagged type ", Id, Prev);
+                     Next (Iface);
+                  end loop;
+               end if;
             end if;
+         end;
+      end if;
+
+      --  Only composite types other than array types are allowed to have
+      --  discriminants.
+
+      if Present (Discriminant_Specifications (N)) then
+         if (Is_Elementary_Type (Parent_Type)
+               or else
+             Is_Array_Type      (Parent_Type))
+           and then not Error_Posted (N)
+         then
+            Error_Msg_N
+              ("elementary or array type cannot have discriminants",
+               Defining_Identifier (First (Discriminant_Specifications (N))));
+            Set_Has_Discriminants (T, False);
+
+         --  The type is allowed to have discriminants
 
          else
-            if Ada_Version >= Ada_2012
-              and then Nkind (N) = N_Private_Type_Declaration
-            then
-               Error_Msg_NE
-                 ("declaration of private } must be a tagged type ", Prev, Id);
-            else
-               Error_Msg_NE
-                 ("full declaration of } must be a tagged type ", Prev, Id);
-            end if;
+            Check_SPARK_05_Restriction ("discriminant type is not allowed", N);
          end if;
-      end Tag_Mismatch;
-
-   --  Start of processing for Find_Type_Name
+      end if;
 
-   begin
-      --  Find incomplete declaration, if one was given
+      --  In Ada 83, a derived type defined in a package specification cannot
+      --  be used for further derivation until the end of its visible part.
+      --  Note that derivation in the private part of the package is allowed.
 
-      Prev := Current_Entity_In_Scope (Id);
+      if Ada_Version = Ada_83
+        and then Is_Derived_Type (Parent_Type)
+        and then In_Visible_Part (Scope (Parent_Type))
+      then
+         if Ada_Version = Ada_83 and then Comes_From_Source (Indic) then
+            Error_Msg_N
+              ("(Ada 83): premature use of type for derivation", Indic);
+         end if;
+      end if;
 
-      --  New type declaration
+      --  Check for early use of incomplete or private type
 
-      if No (Prev) then
-         Enter_Name (Id);
-         return Id;
+      if Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
+         Error_Msg_N ("premature derivation of incomplete type", Indic);
+         return;
 
-      --  Previous declaration exists
+      elsif (Is_Incomplete_Or_Private_Type (Parent_Type)
+              and then not Comes_From_Generic (Parent_Type))
+        or else Has_Private_Component (Parent_Type)
+      then
+         --  The ancestor type of a formal type can be incomplete, in which
+         --  case only the operations of the partial view are available in the
+         --  generic. Subsequent checks may be required when the full view is
+         --  analyzed to verify that a derivation from a tagged type has an
+         --  extension.
 
-      else
-         Prev_Par := Parent (Prev);
+         if Nkind (Original_Node (N)) = N_Formal_Type_Declaration then
+            null;
 
-         --  Error if not incomplete/private case except if previous
-         --  declaration is implicit, etc. Enter_Name will emit error if
-         --  appropriate.
+         elsif No (Underlying_Type (Parent_Type))
+           or else Has_Private_Component (Parent_Type)
+         then
+            Error_Msg_N
+              ("premature derivation of derived or private type", Indic);
 
-         if not Is_Incomplete_Or_Private_Type (Prev) then
-            Enter_Name (Id);
-            New_Id := Id;
+            --  Flag the type itself as being in error, this prevents some
+            --  nasty problems with subsequent uses of the malformed type.
 
-         --  Check invalid completion of private or incomplete type
+            Set_Error_Posted (T);
 
-         elsif not Nkind_In (N, N_Full_Type_Declaration,
-                                N_Task_Type_Declaration,
-                                N_Protected_Type_Declaration)
-           and then
-             (Ada_Version < Ada_2012
-               or else not Is_Incomplete_Type (Prev)
-               or else not Nkind_In (N, N_Private_Type_Declaration,
-                                        N_Private_Extension_Declaration))
-         then
-            --  Completion must be a full type declarations (RM 7.3(4))
+         --  Check that within the immediate scope of an untagged partial
+         --  view it's illegal to derive from the partial view if the
+         --  full view is tagged. (7.3(7))
 
-            Error_Msg_Sloc := Sloc (Prev);
-            Error_Msg_NE ("invalid completion of }", Id, Prev);
+         --  We verify that the Parent_Type is a partial view by checking
+         --  that it is not a Full_Type_Declaration (i.e. a private type or
+         --  private extension declaration), to distinguish a partial view
+         --  from  a derivation from a private type which also appears as
+         --  E_Private_Type. If the parent base type is not declared in an
+         --  enclosing scope there is no need to check.
 
-            --  Set scope of Id to avoid cascaded errors. Entity is never
-            --  examined again, except when saving globals in generics.
+         elsif Present (Full_View (Parent_Type))
+           and then Nkind (Parent (Parent_Type)) /= N_Full_Type_Declaration
+           and then not Is_Tagged_Type (Parent_Type)
+           and then Is_Tagged_Type (Full_View (Parent_Type))
+           and then In_Open_Scopes (Scope (Base_Type (Parent_Type)))
+         then
+            Error_Msg_N
+              ("premature derivation from type with tagged full view",
+                Indic);
+         end if;
+      end if;
 
-            Set_Scope (Id, Current_Scope);
-            New_Id := Id;
+      --  Check that form of derivation is appropriate
 
-            --  If this is a repeated incomplete declaration, no further
-            --  checks are possible.
+      Taggd := Is_Tagged_Type (Parent_Type);
 
-            if Nkind (N) = N_Incomplete_Type_Declaration then
-               return Prev;
-            end if;
+      --  Set the parent type to the class-wide type's specific type in this
+      --  case to prevent cascading errors
 
-         --  Case of full declaration of incomplete type
+      if Present (Extension) and then Is_Class_Wide_Type (Parent_Type) then
+         Error_Msg_N ("parent type must not be a class-wide type", Indic);
+         Set_Etype (T, Etype (Parent_Type));
+         return;
+      end if;
 
-         elsif Ekind (Prev) = E_Incomplete_Type
-           and then (Ada_Version < Ada_2012
-                      or else No (Full_View (Prev))
-                      or else not Is_Private_Type (Full_View (Prev)))
-         then
-            --  Indicate that the incomplete declaration has a matching full
-            --  declaration. The defining occurrence of the incomplete
-            --  declaration remains the visible one, and the procedure
-            --  Get_Full_View dereferences it whenever the type is used.
+      if Present (Extension) and then not Taggd then
+         Error_Msg_N
+           ("type derived from untagged type cannot have extension", Indic);
 
-            if Present (Full_View (Prev)) then
-               Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
-            end if;
+      elsif No (Extension) and then Taggd then
 
-            Set_Full_View (Prev, Id);
-            Append_Entity (Id, Current_Scope);
-            Set_Is_Public (Id, Is_Public (Prev));
-            Set_Is_Internal (Id);
-            New_Id := Prev;
+         --  If this declaration is within a private part (or body) of a
+         --  generic instantiation then the derivation is allowed (the parent
+         --  type can only appear tagged in this case if it's a generic actual
+         --  type, since it would otherwise have been rejected in the analysis
+         --  of the generic template).
 
-            --  If the incomplete view is tagged, a class_wide type has been
-            --  created already. Use it for the private type as well, in order
-            --  to prevent multiple incompatible class-wide types that may be
-            --  created for self-referential anonymous access components.
+         if not Is_Generic_Actual_Type (Parent_Type)
+           or else In_Visible_Part (Scope (Parent_Type))
+         then
+            if Is_Class_Wide_Type (Parent_Type) then
+               Error_Msg_N
+                 ("parent type must not be a class-wide type", Indic);
 
-            if Is_Tagged_Type (Prev)
-              and then Present (Class_Wide_Type (Prev))
-            then
-               Set_Ekind (Id, Ekind (Prev));         --  will be reset later
-               Set_Class_Wide_Type (Id, Class_Wide_Type (Prev));
+               --  Use specific type to prevent cascaded errors.
 
-               --  If the incomplete type is completed by a private declaration
-               --  the class-wide type remains associated with the incomplete
-               --  type, to prevent order-of-elaboration issues in gigi, else
-               --  we associate the class-wide type with the known full view.
+               Parent_Type := Etype (Parent_Type);
 
-               if Nkind (N) /= N_Private_Type_Declaration then
-                  Set_Etype (Class_Wide_Type (Id), Id);
-               end if;
+            else
+               Error_Msg_N
+                 ("type derived from tagged type must have extension", Indic);
             end if;
+         end if;
+      end if;
 
-         --  Case of full declaration of private type
+      --  AI-443: Synchronized formal derived types require a private
+      --  extension. There is no point in checking the ancestor type or
+      --  the progenitors since the construct is wrong to begin with.
 
-         else
-            --  If the private type was a completion of an incomplete type then
-            --  update Prev to reference the private type
+      if Ada_Version >= Ada_2005
+        and then Is_Generic_Type (T)
+        and then Present (Original_Node (N))
+      then
+         declare
+            Decl : constant Node_Id := Original_Node (N);
 
-            if Ada_Version >= Ada_2012
-              and then Ekind (Prev) = E_Incomplete_Type
-              and then Present (Full_View (Prev))
-              and then Is_Private_Type (Full_View (Prev))
-            then
-               Prev := Full_View (Prev);
-               Prev_Par := Parent (Prev);
-            end if;
+         begin
+            if Nkind (Decl) = N_Formal_Type_Declaration
+              and then Nkind (Formal_Type_Definition (Decl)) =
+                                          N_Formal_Derived_Type_Definition
+              and then Synchronized_Present (Formal_Type_Definition (Decl))
+              and then No (Extension)
 
-            if Nkind (N) = N_Full_Type_Declaration
-              and then Nkind_In
-                         (Type_Definition (N), N_Record_Definition,
-                                               N_Derived_Type_Definition)
-              and then Interface_Present (Type_Definition (N))
+               --  Avoid emitting a duplicate error message
+
+              and then not Error_Posted (Indic)
             then
                Error_Msg_N
-                 ("completion of private type cannot be an interface", N);
+                 ("synchronized derived type must have extension", N);
             end if;
+         end;
+      end if;
 
-            if Nkind (Parent (Prev)) /= N_Private_Extension_Declaration then
-               if Etype (Prev) /= Prev then
-
-                  --  Prev is a private subtype or a derived type, and needs
-                  --  no completion.
+      if Null_Exclusion_Present (Def)
+        and then not Is_Access_Type (Parent_Type)
+      then
+         Error_Msg_N ("null exclusion can only apply to an access type", N);
+      end if;
 
-                  Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
-                  New_Id := Id;
+      --  Avoid deriving parent primitives of underlying record views
 
-               elsif Ekind (Prev) = E_Private_Type
-                 and then Nkind_In (N, N_Task_Type_Declaration,
-                                       N_Protected_Type_Declaration)
-               then
-                  Error_Msg_N
-                   ("completion of nonlimited type cannot be limited", N);
+      Build_Derived_Type (N, Parent_Type, T, Is_Completion,
+        Derive_Subps => not Is_Underlying_Record_View (T));
 
-               elsif Ekind (Prev) = E_Record_Type_With_Private
-                 and then Nkind_In (N, N_Task_Type_Declaration,
-                                       N_Protected_Type_Declaration)
-               then
-                  if not Is_Limited_Record (Prev) then
-                     Error_Msg_N
-                        ("completion of nonlimited type cannot be limited", N);
+      --  AI-419: The parent type of an explicitly limited derived type must
+      --  be a limited type or a limited interface.
 
-                  elsif No (Interface_List (N)) then
-                     Error_Msg_N
-                        ("completion of tagged private type must be tagged",
-                         N);
-                  end if;
-               end if;
+      if Limited_Present (Def) then
+         Set_Is_Limited_Record (T);
 
-            --  Ada 2005 (AI-251): Private extension declaration of a task
-            --  type or a protected type. This case arises when covering
-            --  interface types.
+         if Is_Interface (T) then
+            Set_Is_Limited_Interface (T);
+         end if;
 
-            elsif Nkind_In (N, N_Task_Type_Declaration,
-                               N_Protected_Type_Declaration)
-            then
-               null;
+         if not Is_Limited_Type (Parent_Type)
+           and then
+             (not Is_Interface (Parent_Type)
+               or else not Is_Limited_Interface (Parent_Type))
+         then
+            --  AI05-0096: a derivation in the private part of an instance is
+            --  legal if the generic formal is untagged limited, and the actual
+            --  is non-limited.
 
-            elsif Nkind (N) /= N_Full_Type_Declaration
-              or else Nkind (Type_Definition (N)) /= N_Derived_Type_Definition
+            if Is_Generic_Actual_Type (Parent_Type)
+              and then In_Private_Part (Current_Scope)
+              and then
+                not Is_Tagged_Type
+                      (Generic_Parent_Type (Parent (Parent_Type)))
             then
-               Error_Msg_N
-                 ("full view of private extension must be an extension", N);
+               null;
 
-            elsif not (Abstract_Present (Parent (Prev)))
-              and then Abstract_Present (Type_Definition (N))
-            then
-               Error_Msg_N
-                 ("full view of non-abstract extension cannot be abstract", N);
+            else
+               Error_Msg_NE
+                 ("parent type& of limited type must be limited",
+                  N, Parent_Type);
             end if;
+         end if;
+      end if;
 
-            if not In_Private_Part (Current_Scope) then
-               Error_Msg_N
-                 ("declaration of full view must appear in private part", N);
-            end if;
+      --  In SPARK, there are no derived type definitions other than type
+      --  extensions of tagged record types.
 
-            if Ada_Version >= Ada_2012 then
-               Check_Duplicate_Aspects;
-            end if;
+      if No (Extension) then
+         Check_SPARK_05_Restriction
+           ("derived type is not allowed", Original_Node (N));
+      end if;
+   end Derived_Type_Declaration;
 
-            Copy_And_Swap (Prev, Id);
-            Set_Has_Private_Declaration (Prev);
-            Set_Has_Private_Declaration (Id);
+   ------------------------
+   -- Diagnose_Interface --
+   ------------------------
 
-            --  Preserve aspect and iterator flags that may have been set on
-            --  the partial view.
+   procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id) is
+   begin
+      if not Is_Interface (E) and then  E /= Any_Type then
+         Error_Msg_NE ("(Ada 2005) & must be an interface", N, E);
+      end if;
+   end Diagnose_Interface;
 
-            Set_Has_Delayed_Aspects (Prev, Has_Delayed_Aspects (Id));
-            Set_Has_Implicit_Dereference (Prev, Has_Implicit_Dereference (Id));
+   ----------------------------------
+   -- Enumeration_Type_Declaration --
+   ----------------------------------
 
-            --  If no error, propagate freeze_node from private to full view.
-            --  It may have been generated for an early operational item.
+   procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id) is
+      Ev     : Uint;
+      L      : Node_Id;
+      R_Node : Node_Id;
+      B_Node : Node_Id;
 
-            if Present (Freeze_Node (Id))
-              and then Serious_Errors_Detected = 0
-              and then No (Full_View (Id))
-            then
-               Set_Freeze_Node (Prev, Freeze_Node (Id));
-               Set_Freeze_Node (Id, Empty);
-               Set_First_Rep_Item (Prev, First_Rep_Item (Id));
-            end if;
+   begin
+      --  Create identifier node representing lower bound
 
-            Set_Full_View (Id, Prev);
-            New_Id := Prev;
+      B_Node := New_Node (N_Identifier, Sloc (Def));
+      L := First (Literals (Def));
+      Set_Chars (B_Node, Chars (L));
+      Set_Entity (B_Node,  L);
+      Set_Etype (B_Node, T);
+      Set_Is_Static_Expression (B_Node, True);
+
+      R_Node := New_Node (N_Range, Sloc (Def));
+      Set_Low_Bound  (R_Node, B_Node);
+
+      Set_Ekind (T, E_Enumeration_Type);
+      Set_First_Literal (T, L);
+      Set_Etype (T, T);
+      Set_Is_Constrained (T);
+
+      Ev := Uint_0;
+
+      --  Loop through literals of enumeration type setting pos and rep values
+      --  except that if the Ekind is already set, then it means the literal
+      --  was already constructed (case of a derived type declaration and we
+      --  should not disturb the Pos and Rep values.
+
+      while Present (L) loop
+         if Ekind (L) /= E_Enumeration_Literal then
+            Set_Ekind (L, E_Enumeration_Literal);
+            Set_Enumeration_Pos (L, Ev);
+            Set_Enumeration_Rep (L, Ev);
+            Set_Is_Known_Valid  (L, True);
          end if;
 
-         --  Verify that full declaration conforms to partial one
+         Set_Etype (L, T);
+         New_Overloaded_Entity (L);
+         Generate_Definition (L);
+         Set_Convention (L, Convention_Intrinsic);
 
-         if Is_Incomplete_Or_Private_Type (Prev)
-           and then Present (Discriminant_Specifications (Prev_Par))
-         then
-            if Present (Discriminant_Specifications (N)) then
-               if Ekind (Prev) = E_Incomplete_Type then
-                  Check_Discriminant_Conformance (N, Prev, Prev);
-               else
-                  Check_Discriminant_Conformance (N, Prev, Id);
-               end if;
+         --  Case of character literal
 
-            else
-               Error_Msg_N
-                 ("missing discriminants in full type declaration", N);
+         if Nkind (L) = N_Defining_Character_Literal then
+            Set_Is_Character_Type (T, True);
 
-               --  To avoid cascaded errors on subsequent use, share the
-               --  discriminants of the partial view.
+            --  Check violation of No_Wide_Characters
 
-               Set_Discriminant_Specifications (N,
-                 Discriminant_Specifications (Prev_Par));
+            if Restriction_Check_Required (No_Wide_Characters) then
+               Get_Name_String (Chars (L));
+
+               if Name_Len >= 3 and then Name_Buffer (1 .. 2) = "QW" then
+                  Check_Restriction (No_Wide_Characters, L);
+               end if;
             end if;
          end if;
 
-         --  A prior untagged partial view can have an associated class-wide
-         --  type due to use of the class attribute, and in this case the full
-         --  type must also be tagged. This Ada 95 usage is deprecated in favor
-         --  of incomplete tagged declarations, but we check for it.
+         Ev := Ev + 1;
+         Next (L);
+      end loop;
 
-         if Is_Type (Prev)
-           and then (Is_Tagged_Type (Prev)
-                       or else Present (Class_Wide_Type (Prev)))
-         then
-            --  Ada 2012 (AI05-0162): A private type may be the completion of
-            --  an incomplete type.
+      --  Now create a node representing upper bound
 
-            if Ada_Version >= Ada_2012
-              and then Is_Incomplete_Type (Prev)
-              and then Nkind_In (N, N_Private_Type_Declaration,
-                                    N_Private_Extension_Declaration)
-            then
-               --  No need to check private extensions since they are tagged
+      B_Node := New_Node (N_Identifier, Sloc (Def));
+      Set_Chars (B_Node, Chars (Last (Literals (Def))));
+      Set_Entity (B_Node,  Last (Literals (Def)));
+      Set_Etype (B_Node, T);
+      Set_Is_Static_Expression (B_Node, True);
 
-               if Nkind (N) = N_Private_Type_Declaration
-                 and then not Tagged_Present (N)
-               then
-                  Tag_Mismatch;
-               end if;
+      Set_High_Bound (R_Node, B_Node);
 
-            --  The full declaration is either a tagged type (including
-            --  a synchronized type that implements interfaces) or a
-            --  type extension, otherwise this is an error.
+      --  Initialize various fields of the type. Some of this information
+      --  may be overwritten later through rep.clauses.
 
-            elsif Nkind_In (N, N_Task_Type_Declaration,
-                               N_Protected_Type_Declaration)
-            then
-               if No (Interface_List (N))
-                 and then not Error_Posted (N)
-               then
-                  Tag_Mismatch;
-               end if;
+      Set_Scalar_Range    (T, R_Node);
+      Set_RM_Size         (T, UI_From_Int (Minimum_Size (T)));
+      Set_Enum_Esize      (T);
+      Set_Enum_Pos_To_Rep (T, Empty);
 
-            elsif Nkind (Type_Definition (N)) = N_Record_Definition then
+      --  Set Discard_Names if configuration pragma set, or if there is
+      --  a parameterless pragma in the current declarative region
 
-               --  Indicate that the previous declaration (tagged incomplete
-               --  or private declaration) requires the same on the full one.
+      if Global_Discard_Names or else Discard_Names (Scope (T)) then
+         Set_Discard_Names (T);
+      end if;
 
-               if not Tagged_Present (Type_Definition (N)) then
-                  Tag_Mismatch;
-                  Set_Is_Tagged_Type (Id);
-               end if;
+      --  Process end label if there is one
+
+      if Present (Def) then
+         Process_End_Label (Def, 'e', T);
+      end if;
+   end Enumeration_Type_Declaration;
+
+   ---------------------------------
+   -- Expand_To_Stored_Constraint --
+   ---------------------------------
+
+   function Expand_To_Stored_Constraint
+     (Typ        : Entity_Id;
+      Constraint : Elist_Id) return Elist_Id
+   is
+      Explicitly_Discriminated_Type : Entity_Id;
+      Expansion    : Elist_Id;
+      Discriminant : Entity_Id;
 
-            elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
-               if No (Record_Extension_Part (Type_Definition (N))) then
-                  Error_Msg_NE
-                    ("full declaration of } must be a record extension",
-                     Prev, Id);
+      function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id;
+      --  Find the nearest type that actually specifies discriminants
 
-                  --  Set some attributes to produce a usable full view
+      ---------------------------------
+      -- Type_With_Explicit_Discrims --
+      ---------------------------------
 
-                  Set_Is_Tagged_Type (Id);
-               end if;
+      function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id is
+         Typ : constant E := Base_Type (Id);
 
-            else
-               Tag_Mismatch;
+      begin
+         if Ekind (Typ) in Incomplete_Or_Private_Kind then
+            if Present (Full_View (Typ)) then
+               return Type_With_Explicit_Discrims (Full_View (Typ));
+            end if;
+
+         else
+            if Has_Discriminants (Typ) then
+               return Typ;
             end if;
          end if;
 
-         if Present (Prev)
-           and then Nkind (Parent (Prev)) = N_Incomplete_Type_Declaration
-           and then Present (Premature_Use (Parent (Prev)))
-         then
-            Error_Msg_Sloc := Sloc (N);
-            Error_Msg_N
-              ("\full declaration #", Premature_Use (Parent (Prev)));
+         if Etype (Typ) = Typ then
+            return Empty;
+         elsif Has_Discriminants (Typ) then
+            return Typ;
+         else
+            return Type_With_Explicit_Discrims (Etype (Typ));
          end if;
 
-         return New_Id;
+      end Type_With_Explicit_Discrims;
+
+   --  Start of processing for Expand_To_Stored_Constraint
+
+   begin
+      if No (Constraint) or else Is_Empty_Elmt_List (Constraint) then
+         return No_Elist;
       end if;
-   end Find_Type_Name;
 
-   -------------------------
-   -- Find_Type_Of_Object --
-   -------------------------
+      Explicitly_Discriminated_Type := Type_With_Explicit_Discrims (Typ);
 
-   function Find_Type_Of_Object
-     (Obj_Def     : Node_Id;
-      Related_Nod : Node_Id) return Entity_Id
+      if No (Explicitly_Discriminated_Type) then
+         return No_Elist;
+      end if;
+
+      Expansion := New_Elmt_List;
+
+      Discriminant :=
+         First_Stored_Discriminant (Explicitly_Discriminated_Type);
+      while Present (Discriminant) loop
+         Append_Elmt
+           (Get_Discriminant_Value
+              (Discriminant, Explicitly_Discriminated_Type, Constraint),
+            To => Expansion);
+         Next_Stored_Discriminant (Discriminant);
+      end loop;
+
+      return Expansion;
+   end Expand_To_Stored_Constraint;
+
+   ---------------------------
+   -- Find_Hidden_Interface --
+   ---------------------------
+
+   function Find_Hidden_Interface
+     (Src  : Elist_Id;
+      Dest : Elist_Id) return Entity_Id
    is
-      Def_Kind : constant Node_Kind := Nkind (Obj_Def);
-      P        : Node_Id := Parent (Obj_Def);
-      T        : Entity_Id;
-      Nam      : Name_Id;
+      Iface      : Entity_Id;
+      Iface_Elmt : Elmt_Id;
 
    begin
-      --  If the parent is a component_definition node we climb to the
-      --  component_declaration node
+      if Present (Src) and then Present (Dest) then
+         Iface_Elmt := First_Elmt (Src);
+         while Present (Iface_Elmt) loop
+            Iface := Node (Iface_Elmt);
 
-      if Nkind (P) = N_Component_Definition then
-         P := Parent (P);
-      end if;
+            if Is_Interface (Iface)
+              and then not Contain_Interface (Iface, Dest)
+            then
+               return Iface;
+            end if;
 
-      --  Case of an anonymous array subtype
+            Next_Elmt (Iface_Elmt);
+         end loop;
+      end if;
 
-      if Nkind_In (Def_Kind, N_Constrained_Array_Definition,
-                             N_Unconstrained_Array_Definition)
-      then
-         T := Empty;
-         Array_Type_Declaration (T, Obj_Def);
+      return Empty;
+   end Find_Hidden_Interface;
 
-      --  Create an explicit subtype whenever possible
+   --------------------
+   -- Find_Type_Name --
+   --------------------
 
-      elsif Nkind (P) /= N_Component_Declaration
-        and then Def_Kind = N_Subtype_Indication
-      then
-         --  Base name of subtype on object name, which will be unique in
-         --  the current scope.
+   function Find_Type_Name (N : Node_Id) return Entity_Id is
+      Id       : constant Entity_Id := Defining_Identifier (N);
+      Prev     : Entity_Id;
+      New_Id   : Entity_Id;
+      Prev_Par : Node_Id;
 
-         --  If this is a duplicate declaration, return base type, to avoid
-         --  generating duplicate anonymous types.
+      procedure Check_Duplicate_Aspects;
+      --  Check that aspects specified in a completion have not been specified
+      --  already in the partial view. Type_Invariant and others can be
+      --  specified on either view but never on both.
 
-         if Error_Posted (P) then
-            Analyze (Subtype_Mark (Obj_Def));
-            return Entity (Subtype_Mark (Obj_Def));
-         end if;
+      procedure Tag_Mismatch;
+      --  Diagnose a tagged partial view whose full view is untagged.
+      --  We post the message on the full view, with a reference to
+      --  the previous partial view. The partial view can be private
+      --  or incomplete, and these are handled in a different manner,
+      --  so we determine the position of the error message from the
+      --  respective slocs of both.
 
-         Nam :=
-            New_External_Name
-             (Chars (Defining_Identifier (Related_Nod)), 'S', 0, 'T');
+      -----------------------------
+      -- Check_Duplicate_Aspects --
+      -----------------------------
+      procedure Check_Duplicate_Aspects is
+         Prev_Aspects   : constant List_Id := Aspect_Specifications (Prev_Par);
+         Full_Aspects   : constant List_Id := Aspect_Specifications (N);
+         F_Spec, P_Spec : Node_Id;
 
-         T := Make_Defining_Identifier (Sloc (P), Nam);
+      begin
+         if Present (Prev_Aspects) and then Present (Full_Aspects) then
+            F_Spec := First (Full_Aspects);
+            while Present (F_Spec) loop
+               P_Spec := First (Prev_Aspects);
+               while Present (P_Spec) loop
+                  if Chars (Identifier (P_Spec)) = Chars (Identifier (F_Spec))
+                  then
+                     Error_Msg_N
+                       ("aspect already specified in private declaration",
+                         F_Spec);
+                     Remove (F_Spec);
+                     return;
+                  end if;
 
-         Insert_Action (Obj_Def,
-           Make_Subtype_Declaration (Sloc (P),
-             Defining_Identifier => T,
-             Subtype_Indication  => Relocate_Node (Obj_Def)));
+                  Next (P_Spec);
+               end loop;
 
-         --  This subtype may need freezing, and this will not be done
-         --  automatically if the object declaration is not in declarative
-         --  part. Since this is an object declaration, the type cannot always
-         --  be frozen here. Deferred constants do not freeze their type
-         --  (which often enough will be private).
+               Next (F_Spec);
+            end loop;
+         end if;
+      end Check_Duplicate_Aspects;
 
-         if Nkind (P) = N_Object_Declaration
-           and then Constant_Present (P)
-           and then No (Expression (P))
-         then
-            null;
+      ------------------
+      -- Tag_Mismatch --
+      ------------------
 
-         --  Here we freeze the base type of object type to catch premature use
-         --  of discriminated private type without a full view.
+      procedure Tag_Mismatch is
+      begin
+         if Sloc (Prev) < Sloc (Id) then
+            if Ada_Version >= Ada_2012
+              and then Nkind (N) = N_Private_Type_Declaration
+            then
+               Error_Msg_NE
+                 ("declaration of private } must be a tagged type ", Id, Prev);
+            else
+               Error_Msg_NE
+                 ("full declaration of } must be a tagged type ", Id, Prev);
+            end if;
 
          else
-            Insert_Actions (Obj_Def, Freeze_Entity (Base_Type (T), P));
+            if Ada_Version >= Ada_2012
+              and then Nkind (N) = N_Private_Type_Declaration
+            then
+               Error_Msg_NE
+                 ("declaration of private } must be a tagged type ", Prev, Id);
+            else
+               Error_Msg_NE
+                 ("full declaration of } must be a tagged type ", Prev, Id);
+            end if;
          end if;
+      end Tag_Mismatch;
 
-      --  Ada 2005 AI-406: the object definition in an object declaration
-      --  can be an access definition.
-
-      elsif Def_Kind = N_Access_Definition then
-         T := Access_Definition (Related_Nod, Obj_Def);
-
-         Set_Is_Local_Anonymous_Access
-           (T,
-            V => (Ada_Version < Ada_2012)
-                   or else (Nkind (P) /= N_Object_Declaration)
-                   or else Is_Library_Level_Entity (Defining_Identifier (P)));
+   --  Start of processing for Find_Type_Name
 
-      --  Otherwise, the object definition is just a subtype_mark
+   begin
+      --  Find incomplete declaration, if one was given
 
-      else
-         T := Process_Subtype (Obj_Def, Related_Nod);
+      Prev := Current_Entity_In_Scope (Id);
 
-         --  If expansion is disabled an object definition that is an aggregate
-         --  will not get expanded and may lead to scoping problems in the back
-         --  end, if the object is referenced in an inner scope. In that case
-         --  create an itype reference for the object definition now. This
-         --  may be redundant in some cases, but harmless.
+      --  New type declaration
 
-         if Is_Itype (T)
-           and then Nkind (Related_Nod) = N_Object_Declaration
-           and then ASIS_Mode
-         then
-            Build_Itype_Reference (T, Related_Nod);
-         end if;
-      end if;
+      if No (Prev) then
+         Enter_Name (Id);
+         return Id;
 
-      return T;
-   end Find_Type_Of_Object;
+      --  Previous declaration exists
 
-   --------------------------------
-   -- Find_Type_Of_Subtype_Indic --
-   --------------------------------
+      else
+         Prev_Par := Parent (Prev);
 
-   function Find_Type_Of_Subtype_Indic (S : Node_Id) return Entity_Id is
-      Typ : Entity_Id;
+         --  Error if not incomplete/private case except if previous
+         --  declaration is implicit, etc. Enter_Name will emit error if
+         --  appropriate.
 
-   begin
-      --  Case of subtype mark with a constraint
+         if not Is_Incomplete_Or_Private_Type (Prev) then
+            Enter_Name (Id);
+            New_Id := Id;
 
-      if Nkind (S) = N_Subtype_Indication then
-         Find_Type (Subtype_Mark (S));
-         Typ := Entity (Subtype_Mark (S));
+         --  Check invalid completion of private or incomplete type
 
-         if not
-           Is_Valid_Constraint_Kind (Ekind (Typ), Nkind (Constraint (S)))
+         elsif not Nkind_In (N, N_Full_Type_Declaration,
+                                N_Task_Type_Declaration,
+                                N_Protected_Type_Declaration)
+           and then
+             (Ada_Version < Ada_2012
+               or else not Is_Incomplete_Type (Prev)
+               or else not Nkind_In (N, N_Private_Type_Declaration,
+                                        N_Private_Extension_Declaration))
          then
-            Error_Msg_N
-              ("incorrect constraint for this kind of type", Constraint (S));
-            Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
-         end if;
+            --  Completion must be a full type declarations (RM 7.3(4))
 
-      --  Otherwise we have a subtype mark without a constraint
+            Error_Msg_Sloc := Sloc (Prev);
+            Error_Msg_NE ("invalid completion of }", Id, Prev);
 
-      elsif Error_Posted (S) then
-         Rewrite (S, New_Occurrence_Of (Any_Id, Sloc (S)));
-         return Any_Type;
+            --  Set scope of Id to avoid cascaded errors. Entity is never
+            --  examined again, except when saving globals in generics.
 
-      else
-         Find_Type (S);
-         Typ := Entity (S);
-      end if;
+            Set_Scope (Id, Current_Scope);
+            New_Id := Id;
 
-      --  Check No_Wide_Characters restriction
+            --  If this is a repeated incomplete declaration, no further
+            --  checks are possible.
 
-      Check_Wide_Character_Restriction (Typ, S);
+            if Nkind (N) = N_Incomplete_Type_Declaration then
+               return Prev;
+            end if;
 
-      return Typ;
-   end Find_Type_Of_Subtype_Indic;
+         --  Case of full declaration of incomplete type
 
-   -------------------------------------
-   -- Floating_Point_Type_Declaration --
-   -------------------------------------
+         elsif Ekind (Prev) = E_Incomplete_Type
+           and then (Ada_Version < Ada_2012
+                      or else No (Full_View (Prev))
+                      or else not Is_Private_Type (Full_View (Prev)))
+         then
+            --  Indicate that the incomplete declaration has a matching full
+            --  declaration. The defining occurrence of the incomplete
+            --  declaration remains the visible one, and the procedure
+            --  Get_Full_View dereferences it whenever the type is used.
 
-   procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id) is
-      Digs          : constant Node_Id := Digits_Expression (Def);
-      Max_Digs_Val  : constant Uint := Digits_Value (Standard_Long_Long_Float);
-      Digs_Val      : Uint;
-      Base_Typ      : Entity_Id;
-      Implicit_Base : Entity_Id;
-      Bound         : Node_Id;
+            if Present (Full_View (Prev)) then
+               Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
+            end if;
 
-      function Can_Derive_From (E : Entity_Id) return Boolean;
-      --  Find if given digits value, and possibly a specified range, allows
-      --  derivation from specified type
+            Set_Full_View (Prev, Id);
+            Append_Entity (Id, Current_Scope);
+            Set_Is_Public (Id, Is_Public (Prev));
+            Set_Is_Internal (Id);
+            New_Id := Prev;
 
-      function Find_Base_Type return Entity_Id;
-      --  Find a predefined base type that Def can derive from, or generate
-      --  an error and substitute Long_Long_Float if none exists.
+            --  If the incomplete view is tagged, a class_wide type has been
+            --  created already. Use it for the private type as well, in order
+            --  to prevent multiple incompatible class-wide types that may be
+            --  created for self-referential anonymous access components.
 
-      ---------------------
-      -- Can_Derive_From --
-      ---------------------
+            if Is_Tagged_Type (Prev)
+              and then Present (Class_Wide_Type (Prev))
+            then
+               Set_Ekind (Id, Ekind (Prev));         --  will be reset later
+               Set_Class_Wide_Type (Id, Class_Wide_Type (Prev));
 
-      function Can_Derive_From (E : Entity_Id) return Boolean is
-         Spec : constant Entity_Id := Real_Range_Specification (Def);
+               --  The type of the classwide type is the current Id. Previously
+               --  this was not done for private declarations because of order-
+               --  of elaboration issues in the back-end, but gigi now handles
+               --  this properly.
 
-      begin
-         --  Check specified "digits" constraint
+               Set_Etype (Class_Wide_Type (Id), Id);
+            end if;
 
-         if Digs_Val > Digits_Value (E) then
-            return False;
-         end if;
+         --  Case of full declaration of private type
 
-         --  Check for matching range, if specified
+         else
+            --  If the private type was a completion of an incomplete type then
+            --  update Prev to reference the private type
 
-         if Present (Spec) then
-            if Expr_Value_R (Type_Low_Bound (E)) >
-               Expr_Value_R (Low_Bound (Spec))
+            if Ada_Version >= Ada_2012
+              and then Ekind (Prev) = E_Incomplete_Type
+              and then Present (Full_View (Prev))
+              and then Is_Private_Type (Full_View (Prev))
             then
-               return False;
+               Prev := Full_View (Prev);
+               Prev_Par := Parent (Prev);
             end if;
 
-            if Expr_Value_R (Type_High_Bound (E)) <
-               Expr_Value_R (High_Bound (Spec))
+            if Nkind (N) = N_Full_Type_Declaration
+              and then Nkind_In
+                         (Type_Definition (N), N_Record_Definition,
+                                               N_Derived_Type_Definition)
+              and then Interface_Present (Type_Definition (N))
             then
-               return False;
+               Error_Msg_N
+                 ("completion of private type cannot be an interface", N);
             end if;
-         end if;
 
-         return True;
-      end Can_Derive_From;
+            if Nkind (Parent (Prev)) /= N_Private_Extension_Declaration then
+               if Etype (Prev) /= Prev then
 
-      --------------------
-      -- Find_Base_Type --
-      --------------------
+                  --  Prev is a private subtype or a derived type, and needs
+                  --  no completion.
 
-      function Find_Base_Type return Entity_Id is
-         Choice : Elmt_Id := First_Elmt (Predefined_Float_Types);
+                  Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
+                  New_Id := Id;
 
-      begin
-         --  Iterate over the predefined types in order, returning the first
-         --  one that Def can derive from.
+               elsif Ekind (Prev) = E_Private_Type
+                 and then Nkind_In (N, N_Task_Type_Declaration,
+                                       N_Protected_Type_Declaration)
+               then
+                  Error_Msg_N
+                   ("completion of nonlimited type cannot be limited", N);
 
-         while Present (Choice) loop
-            if Can_Derive_From (Node (Choice)) then
-               return Node (Choice);
+               elsif Ekind (Prev) = E_Record_Type_With_Private
+                 and then Nkind_In (N, N_Task_Type_Declaration,
+                                       N_Protected_Type_Declaration)
+               then
+                  if not Is_Limited_Record (Prev) then
+                     Error_Msg_N
+                        ("completion of nonlimited type cannot be limited", N);
+
+                  elsif No (Interface_List (N)) then
+                     Error_Msg_N
+                        ("completion of tagged private type must be tagged",
+                         N);
+                  end if;
+               end if;
+
+            --  Ada 2005 (AI-251): Private extension declaration of a task
+            --  type or a protected type. This case arises when covering
+            --  interface types.
+
+            elsif Nkind_In (N, N_Task_Type_Declaration,
+                               N_Protected_Type_Declaration)
+            then
+               null;
+
+            elsif Nkind (N) /= N_Full_Type_Declaration
+              or else Nkind (Type_Definition (N)) /= N_Derived_Type_Definition
+            then
+               Error_Msg_N
+                 ("full view of private extension must be an extension", N);
+
+            elsif not (Abstract_Present (Parent (Prev)))
+              and then Abstract_Present (Type_Definition (N))
+            then
+               Error_Msg_N
+                 ("full view of non-abstract extension cannot be abstract", N);
             end if;
 
-            Next_Elmt (Choice);
-         end loop;
+            if not In_Private_Part (Current_Scope) then
+               Error_Msg_N
+                 ("declaration of full view must appear in private part", N);
+            end if;
 
-         --  If we can't derive from any existing type, use Long_Long_Float
-         --  and give appropriate message explaining the problem.
+            if Ada_Version >= Ada_2012 then
+               Check_Duplicate_Aspects;
+            end if;
 
-         if Digs_Val > Max_Digs_Val then
-            --  It might be the case that there is a type with the requested
-            --  range, just not the combination of digits and range.
+            Copy_And_Swap (Prev, Id);
+            Set_Has_Private_Declaration (Prev);
+            Set_Has_Private_Declaration (Id);
 
-            Error_Msg_N
-              ("no predefined type has requested range and precision",
-               Real_Range_Specification (Def));
+            --  AI12-0133: Indicate whether we have a partial view with
+            --  unknown discriminants, in which case initialization of objects
+            --  of the type do not receive an invariant check.
 
-         else
-            Error_Msg_N
-              ("range too large for any predefined type",
-               Real_Range_Specification (Def));
-         end if;
+            Set_Partial_View_Has_Unknown_Discr
+              (Prev, Has_Unknown_Discriminants (Id));
 
-         return Standard_Long_Long_Float;
-      end Find_Base_Type;
+            --  Preserve aspect and iterator flags that may have been set on
+            --  the partial view.
 
-   --  Start of processing for Floating_Point_Type_Declaration
+            Set_Has_Delayed_Aspects (Prev, Has_Delayed_Aspects (Id));
+            Set_Has_Implicit_Dereference (Prev, Has_Implicit_Dereference (Id));
 
-   begin
-      Check_Restriction (No_Floating_Point, Def);
+            --  If no error, propagate freeze_node from private to full view.
+            --  It may have been generated for an early operational item.
 
-      --  Create an implicit base type
+            if Present (Freeze_Node (Id))
+              and then Serious_Errors_Detected = 0
+              and then No (Full_View (Id))
+            then
+               Set_Freeze_Node (Prev, Freeze_Node (Id));
+               Set_Freeze_Node (Id, Empty);
+               Set_First_Rep_Item (Prev, First_Rep_Item (Id));
+            end if;
 
-      Implicit_Base :=
-        Create_Itype (E_Floating_Point_Type, Parent (Def), T, 'B');
+            Set_Full_View (Id, Prev);
+            New_Id := Prev;
+         end if;
+
+         --  Verify that full declaration conforms to partial one
+
+         if Is_Incomplete_Or_Private_Type (Prev)
+           and then Present (Discriminant_Specifications (Prev_Par))
+         then
+            if Present (Discriminant_Specifications (N)) then
+               if Ekind (Prev) = E_Incomplete_Type then
+                  Check_Discriminant_Conformance (N, Prev, Prev);
+               else
+                  Check_Discriminant_Conformance (N, Prev, Id);
+               end if;
 
-      --  Analyze and verify digits value
+            else
+               Error_Msg_N
+                 ("missing discriminants in full type declaration", N);
 
-      Analyze_And_Resolve (Digs, Any_Integer);
-      Check_Digits_Expression (Digs);
-      Digs_Val := Expr_Value (Digs);
+               --  To avoid cascaded errors on subsequent use, share the
+               --  discriminants of the partial view.
 
-      --  Process possible range spec and find correct type to derive from
+               Set_Discriminant_Specifications (N,
+                 Discriminant_Specifications (Prev_Par));
+            end if;
+         end if;
 
-      Process_Real_Range_Specification (Def);
+         --  A prior untagged partial view can have an associated class-wide
+         --  type due to use of the class attribute, and in this case the full
+         --  type must also be tagged. This Ada 95 usage is deprecated in favor
+         --  of incomplete tagged declarations, but we check for it.
 
-      --  Check that requested number of digits is not too high.
+         if Is_Type (Prev)
+           and then (Is_Tagged_Type (Prev)
+                      or else Present (Class_Wide_Type (Prev)))
+         then
+            --  Ada 2012 (AI05-0162): A private type may be the completion of
+            --  an incomplete type.
 
-      if Digs_Val > Max_Digs_Val then
-         --  The check for Max_Base_Digits may be somewhat expensive, as it
-         --  requires reading System, so only do it when necessary.
+            if Ada_Version >= Ada_2012
+              and then Is_Incomplete_Type (Prev)
+              and then Nkind_In (N, N_Private_Type_Declaration,
+                                    N_Private_Extension_Declaration)
+            then
+               --  No need to check private extensions since they are tagged
 
-         declare
-            Max_Base_Digits : constant Uint :=
-                                Expr_Value
-                                  (Expression
-                                     (Parent (RTE (RE_Max_Base_Digits))));
+               if Nkind (N) = N_Private_Type_Declaration
+                 and then not Tagged_Present (N)
+               then
+                  Tag_Mismatch;
+               end if;
 
-         begin
-            if Digs_Val > Max_Base_Digits then
-               Error_Msg_Uint_1 := Max_Base_Digits;
-               Error_Msg_N ("digits value out of range, maximum is ^", Digs);
+            --  The full declaration is either a tagged type (including
+            --  a synchronized type that implements interfaces) or a
+            --  type extension, otherwise this is an error.
 
-            elsif No (Real_Range_Specification (Def)) then
-               Error_Msg_Uint_1 := Max_Digs_Val;
-               Error_Msg_N ("types with more than ^ digits need range spec "
-                 & "(RM 3.5.7(6))", Digs);
-            end if;
-         end;
-      end if;
+            elsif Nkind_In (N, N_Task_Type_Declaration,
+                               N_Protected_Type_Declaration)
+            then
+               if No (Interface_List (N)) and then not Error_Posted (N) then
+                  Tag_Mismatch;
+               end if;
 
-      --  Find a suitable type to derive from or complain and use a substitute
+            elsif Nkind (Type_Definition (N)) = N_Record_Definition then
 
-      Base_Typ := Find_Base_Type;
+               --  Indicate that the previous declaration (tagged incomplete
+               --  or private declaration) requires the same on the full one.
 
-      --  If there are bounds given in the declaration use them as the bounds
-      --  of the type, otherwise use the bounds of the predefined base type
-      --  that was chosen based on the Digits value.
+               if not Tagged_Present (Type_Definition (N)) then
+                  Tag_Mismatch;
+                  Set_Is_Tagged_Type (Id);
+               end if;
 
-      if Present (Real_Range_Specification (Def)) then
-         Set_Scalar_Range (T, Real_Range_Specification (Def));
-         Set_Is_Constrained (T);
+            elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
+               if No (Record_Extension_Part (Type_Definition (N))) then
+                  Error_Msg_NE
+                    ("full declaration of } must be a record extension",
+                     Prev, Id);
 
-         --  The bounds of this range must be converted to machine numbers
-         --  in accordance with RM 4.9(38).
+                  --  Set some attributes to produce a usable full view
 
-         Bound := Type_Low_Bound (T);
+                  Set_Is_Tagged_Type (Id);
+               end if;
 
-         if Nkind (Bound) = N_Real_Literal then
-            Set_Realval
-              (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
-            Set_Is_Machine_Number (Bound);
+            else
+               Tag_Mismatch;
+            end if;
          end if;
 
-         Bound := Type_High_Bound (T);
-
-         if Nkind (Bound) = N_Real_Literal then
-            Set_Realval
-              (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
-            Set_Is_Machine_Number (Bound);
+         if Present (Prev)
+           and then Nkind (Parent (Prev)) = N_Incomplete_Type_Declaration
+           and then Present (Premature_Use (Parent (Prev)))
+         then
+            Error_Msg_Sloc := Sloc (N);
+            Error_Msg_N
+              ("\full declaration #", Premature_Use (Parent (Prev)));
          end if;
 
-      else
-         Set_Scalar_Range (T, Scalar_Range (Base_Typ));
+         return New_Id;
       end if;
+   end Find_Type_Name;
 
-      --  Complete definition of implicit base and declared first subtype
-
-      Set_Etype          (Implicit_Base, Base_Typ);
-
-      Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
-      Set_Size_Info      (Implicit_Base,                (Base_Typ));
-      Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
-      Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
-      Set_Digits_Value   (Implicit_Base, Digits_Value   (Base_Typ));
-      Set_Float_Rep      (Implicit_Base, Float_Rep      (Base_Typ));
-
-      Set_Ekind          (T, E_Floating_Point_Subtype);
-      Set_Etype          (T, Implicit_Base);
-
-      Set_Size_Info      (T,                (Implicit_Base));
-      Set_RM_Size        (T, RM_Size        (Implicit_Base));
-      Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
-      Set_Digits_Value   (T, Digs_Val);
-   end Floating_Point_Type_Declaration;
-
-   ----------------------------
-   -- Get_Discriminant_Value --
-   ----------------------------
-
-   --  This is the situation:
+   -------------------------
+   -- Find_Type_Of_Object --
+   -------------------------
 
-   --  There is a non-derived type
+   function Find_Type_Of_Object
+     (Obj_Def     : Node_Id;
+      Related_Nod : Node_Id) return Entity_Id
+   is
+      Def_Kind : constant Node_Kind := Nkind (Obj_Def);
+      P        : Node_Id := Parent (Obj_Def);
+      T        : Entity_Id;
+      Nam      : Name_Id;
 
-   --       type T0 (Dx, Dy, Dz...)
+   begin
+      --  If the parent is a component_definition node we climb to the
+      --  component_declaration node
 
-   --  There are zero or more levels of derivation, with each derivation
-   --  either purely inheriting the discriminants, or defining its own.
+      if Nkind (P) = N_Component_Definition then
+         P := Parent (P);
+      end if;
 
-   --       type Ti      is new Ti-1
-   --  or
-   --       type Ti (Dw) is new Ti-1(Dw, 1, X+Y)
-   --  or
-   --       subtype Ti is ...
+      --  Case of an anonymous array subtype
 
-   --  The subtype issue is avoided by the use of Original_Record_Component,
-   --  and the fact that derived subtypes also derive the constraints.
+      if Nkind_In (Def_Kind, N_Constrained_Array_Definition,
+                             N_Unconstrained_Array_Definition)
+      then
+         T := Empty;
+         Array_Type_Declaration (T, Obj_Def);
 
-   --  This chain leads back from
+      --  Create an explicit subtype whenever possible
 
-   --       Typ_For_Constraint
+      elsif Nkind (P) /= N_Component_Declaration
+        and then Def_Kind = N_Subtype_Indication
+      then
+         --  Base name of subtype on object name, which will be unique in
+         --  the current scope.
 
-   --  Typ_For_Constraint has discriminants, and the value for each
-   --  discriminant is given by its corresponding Elmt of Constraints.
+         --  If this is a duplicate declaration, return base type, to avoid
+         --  generating duplicate anonymous types.
 
-   --  Discriminant is some discriminant in this hierarchy
+         if Error_Posted (P) then
+            Analyze (Subtype_Mark (Obj_Def));
+            return Entity (Subtype_Mark (Obj_Def));
+         end if;
 
-   --  We need to return its value
+         Nam :=
+            New_External_Name
+             (Chars (Defining_Identifier (Related_Nod)), 'S', 0, 'T');
 
-   --  We do this by recursively searching each level, and looking for
-   --  Discriminant. Once we get to the bottom, we start backing up
-   --  returning the value for it which may in turn be a discriminant
-   --  further up, so on the backup we continue the substitution.
+         T := Make_Defining_Identifier (Sloc (P), Nam);
 
-   function Get_Discriminant_Value
-     (Discriminant       : Entity_Id;
-      Typ_For_Constraint : Entity_Id;
-      Constraint         : Elist_Id) return Node_Id
-   is
-      function Root_Corresponding_Discriminant
-        (Discr : Entity_Id) return Entity_Id;
-      --  Given a discriminant, traverse the chain of inherited discriminants
-      --  and return the topmost discriminant.
+         Insert_Action (Obj_Def,
+           Make_Subtype_Declaration (Sloc (P),
+             Defining_Identifier => T,
+             Subtype_Indication  => Relocate_Node (Obj_Def)));
 
-      function Search_Derivation_Levels
-        (Ti                    : Entity_Id;
-         Discrim_Values        : Elist_Id;
-         Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id;
-      --  This is the routine that performs the recursive search of levels
-      --  as described above.
+         --  This subtype may need freezing, and this will not be done
+         --  automatically if the object declaration is not in declarative
+         --  part. Since this is an object declaration, the type cannot always
+         --  be frozen here. Deferred constants do not freeze their type
+         --  (which often enough will be private).
 
-      -------------------------------------
-      -- Root_Corresponding_Discriminant --
-      -------------------------------------
+         if Nkind (P) = N_Object_Declaration
+           and then Constant_Present (P)
+           and then No (Expression (P))
+         then
+            null;
 
-      function Root_Corresponding_Discriminant
-        (Discr : Entity_Id) return Entity_Id
-      is
-         D : Entity_Id;
+         --  Here we freeze the base type of object type to catch premature use
+         --  of discriminated private type without a full view.
 
-      begin
-         D := Discr;
-         while Present (Corresponding_Discriminant (D)) loop
-            D := Corresponding_Discriminant (D);
-         end loop;
+         else
+            Insert_Actions (Obj_Def, Freeze_Entity (Base_Type (T), P));
+         end if;
 
-         return D;
-      end Root_Corresponding_Discriminant;
+      --  Ada 2005 AI-406: the object definition in an object declaration
+      --  can be an access definition.
 
-      ------------------------------
-      -- Search_Derivation_Levels --
-      ------------------------------
+      elsif Def_Kind = N_Access_Definition then
+         T := Access_Definition (Related_Nod, Obj_Def);
 
-      function Search_Derivation_Levels
-        (Ti                    : Entity_Id;
-         Discrim_Values        : Elist_Id;
-         Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id
-      is
-         Assoc          : Elmt_Id;
-         Disc           : Entity_Id;
-         Result         : Node_Or_Entity_Id;
-         Result_Entity  : Node_Id;
+         Set_Is_Local_Anonymous_Access
+           (T,
+            V => (Ada_Version < Ada_2012)
+                   or else (Nkind (P) /= N_Object_Declaration)
+                   or else Is_Library_Level_Entity (Defining_Identifier (P)));
 
-      begin
-         --  If inappropriate type, return Error, this happens only in
-         --  cascaded error situations, and we want to avoid a blow up.
+      --  Otherwise, the object definition is just a subtype_mark
 
-         if not Is_Composite_Type (Ti) or else Is_Array_Type (Ti) then
-            return Error;
-         end if;
+      else
+         T := Process_Subtype (Obj_Def, Related_Nod);
 
-         --  Look deeper if possible. Use Stored_Constraints only for
-         --  untagged types. For tagged types use the given constraint.
-         --  This asymmetry needs explanation???
+         --  If expansion is disabled an object definition that is an aggregate
+         --  will not get expanded and may lead to scoping problems in the back
+         --  end, if the object is referenced in an inner scope. In that case
+         --  create an itype reference for the object definition now. This
+         --  may be redundant in some cases, but harmless.
 
-         if not Stored_Discrim_Values
-           and then Present (Stored_Constraint (Ti))
-           and then not Is_Tagged_Type (Ti)
+         if Is_Itype (T)
+           and then Nkind (Related_Nod) = N_Object_Declaration
+           and then ASIS_Mode
          then
-            Result :=
-              Search_Derivation_Levels (Ti, Stored_Constraint (Ti), True);
-         else
-            declare
-               Td : constant Entity_Id := Etype (Ti);
-
-            begin
-               if Td = Ti then
-                  Result := Discriminant;
-
-               else
-                  if Present (Stored_Constraint (Ti)) then
-                     Result :=
-                        Search_Derivation_Levels
-                          (Td, Stored_Constraint (Ti), True);
-                  else
-                     Result :=
-                        Search_Derivation_Levels
-                          (Td, Discrim_Values, Stored_Discrim_Values);
-                  end if;
-               end if;
-            end;
+            Build_Itype_Reference (T, Related_Nod);
          end if;
+      end if;
 
-         --  Extra underlying places to search, if not found above. For
-         --  concurrent types, the relevant discriminant appears in the
-         --  corresponding record. For a type derived from a private type
-         --  without discriminant, the full view inherits the discriminants
-         --  of the full view of the parent.
-
-         if Result = Discriminant then
-            if Is_Concurrent_Type (Ti)
-              and then Present (Corresponding_Record_Type (Ti))
-            then
-               Result :=
-                 Search_Derivation_Levels (
-                   Corresponding_Record_Type (Ti),
-                   Discrim_Values,
-                   Stored_Discrim_Values);
+      return T;
+   end Find_Type_Of_Object;
 
-            elsif Is_Private_Type (Ti)
-              and then not Has_Discriminants (Ti)
-              and then Present (Full_View (Ti))
-              and then Etype (Full_View (Ti)) /= Ti
-            then
-               Result :=
-                 Search_Derivation_Levels (
-                   Full_View (Ti),
-                   Discrim_Values,
-                   Stored_Discrim_Values);
-            end if;
-         end if;
+   --------------------------------
+   -- Find_Type_Of_Subtype_Indic --
+   --------------------------------
 
-         --  If Result is not a (reference to a) discriminant, return it,
-         --  otherwise set Result_Entity to the discriminant.
+   function Find_Type_Of_Subtype_Indic (S : Node_Id) return Entity_Id is
+      Typ : Entity_Id;
 
-         if Nkind (Result) = N_Defining_Identifier then
-            pragma Assert (Result = Discriminant);
-            Result_Entity := Result;
+   begin
+      --  Case of subtype mark with a constraint
 
-         else
-            if not Denotes_Discriminant (Result) then
-               return Result;
-            end if;
+      if Nkind (S) = N_Subtype_Indication then
+         Find_Type (Subtype_Mark (S));
+         Typ := Entity (Subtype_Mark (S));
 
-            Result_Entity := Entity (Result);
+         if not
+           Is_Valid_Constraint_Kind (Ekind (Typ), Nkind (Constraint (S)))
+         then
+            Error_Msg_N
+              ("incorrect constraint for this kind of type", Constraint (S));
+            Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
          end if;
 
-         --  See if this level of derivation actually has discriminants
-         --  because tagged derivations can add them, hence the lower
-         --  levels need not have any.
+      --  Otherwise we have a subtype mark without a constraint
 
-         if not Has_Discriminants (Ti) then
-            return Result;
-         end if;
+      elsif Error_Posted (S) then
+         Rewrite (S, New_Occurrence_Of (Any_Id, Sloc (S)));
+         return Any_Type;
 
-         --  Scan Ti's discriminants for Result_Entity,
-         --  and return its corresponding value, if any.
+      else
+         Find_Type (S);
+         Typ := Entity (S);
+      end if;
 
-         Result_Entity := Original_Record_Component (Result_Entity);
+      --  Check No_Wide_Characters restriction
 
-         Assoc := First_Elmt (Discrim_Values);
+      Check_Wide_Character_Restriction (Typ, S);
 
-         if Stored_Discrim_Values then
-            Disc := First_Stored_Discriminant (Ti);
-         else
-            Disc := First_Discriminant (Ti);
-         end if;
+      return Typ;
+   end Find_Type_Of_Subtype_Indic;
 
-         while Present (Disc) loop
-            pragma Assert (Present (Assoc));
+   -------------------------------------
+   -- Floating_Point_Type_Declaration --
+   -------------------------------------
 
-            if Original_Record_Component (Disc) = Result_Entity then
-               return Node (Assoc);
-            end if;
+   procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id) is
+      Digs          : constant Node_Id := Digits_Expression (Def);
+      Max_Digs_Val  : constant Uint := Digits_Value (Standard_Long_Long_Float);
+      Digs_Val      : Uint;
+      Base_Typ      : Entity_Id;
+      Implicit_Base : Entity_Id;
+      Bound         : Node_Id;
 
-            Next_Elmt (Assoc);
+      function Can_Derive_From (E : Entity_Id) return Boolean;
+      --  Find if given digits value, and possibly a specified range, allows
+      --  derivation from specified type
 
-            if Stored_Discrim_Values then
-               Next_Stored_Discriminant (Disc);
-            else
-               Next_Discriminant (Disc);
-            end if;
-         end loop;
+      function Find_Base_Type return Entity_Id;
+      --  Find a predefined base type that Def can derive from, or generate
+      --  an error and substitute Long_Long_Float if none exists.
 
-         --  Could not find it
-         --
-         return Result;
-      end Search_Derivation_Levels;
+      ---------------------
+      -- Can_Derive_From --
+      ---------------------
 
-      --  Local Variables
+      function Can_Derive_From (E : Entity_Id) return Boolean is
+         Spec : constant Entity_Id := Real_Range_Specification (Def);
 
-      Result : Node_Or_Entity_Id;
+      begin
+         --  Check specified "digits" constraint
 
-   --  Start of processing for Get_Discriminant_Value
+         if Digs_Val > Digits_Value (E) then
+            return False;
+         end if;
 
-   begin
-      --  ??? This routine is a gigantic mess and will be deleted. For the
-      --  time being just test for the trivial case before calling recurse.
+         --  Check for matching range, if specified
 
-      if Base_Type (Scope (Discriminant)) = Base_Type (Typ_For_Constraint) then
-         declare
-            D : Entity_Id;
-            E : Elmt_Id;
+         if Present (Spec) then
+            if Expr_Value_R (Type_Low_Bound (E)) >
+               Expr_Value_R (Low_Bound (Spec))
+            then
+               return False;
+            end if;
 
-         begin
-            D := First_Discriminant (Typ_For_Constraint);
-            E := First_Elmt (Constraint);
-            while Present (D) loop
-               if Chars (D) = Chars (Discriminant) then
-                  return Node (E);
-               end if;
+            if Expr_Value_R (Type_High_Bound (E)) <
+               Expr_Value_R (High_Bound (Spec))
+            then
+               return False;
+            end if;
+         end if;
 
-               Next_Discriminant (D);
-               Next_Elmt (E);
-            end loop;
-         end;
-      end if;
+         return True;
+      end Can_Derive_From;
 
-      Result := Search_Derivation_Levels
-        (Typ_For_Constraint, Constraint, False);
+      --------------------
+      -- Find_Base_Type --
+      --------------------
 
-      --  ??? hack to disappear when this routine is gone
+      function Find_Base_Type return Entity_Id is
+         Choice : Elmt_Id := First_Elmt (Predefined_Float_Types);
 
-      if Nkind (Result) = N_Defining_Identifier then
-         declare
-            D : Entity_Id;
-            E : Elmt_Id;
+      begin
+         --  Iterate over the predefined types in order, returning the first
+         --  one that Def can derive from.
 
-         begin
-            D := First_Discriminant (Typ_For_Constraint);
-            E := First_Elmt (Constraint);
-            while Present (D) loop
-               if Root_Corresponding_Discriminant (D) = Discriminant then
-                  return Node (E);
-               end if;
+         while Present (Choice) loop
+            if Can_Derive_From (Node (Choice)) then
+               return Node (Choice);
+            end if;
 
-               Next_Discriminant (D);
-               Next_Elmt (E);
-            end loop;
-         end;
-      end if;
+            Next_Elmt (Choice);
+         end loop;
 
-      pragma Assert (Nkind (Result) /= N_Defining_Identifier);
-      return Result;
-   end Get_Discriminant_Value;
+         --  If we can't derive from any existing type, use Long_Long_Float
+         --  and give appropriate message explaining the problem.
 
-   --------------------------
-   -- Has_Range_Constraint --
-   --------------------------
+         if Digs_Val > Max_Digs_Val then
+            --  It might be the case that there is a type with the requested
+            --  range, just not the combination of digits and range.
+
+            Error_Msg_N
+              ("no predefined type has requested range and precision",
+               Real_Range_Specification (Def));
+
+         else
+            Error_Msg_N
+              ("range too large for any predefined type",
+               Real_Range_Specification (Def));
+         end if;
 
-   function Has_Range_Constraint (N : Node_Id) return Boolean is
-      C : constant Node_Id := Constraint (N);
+         return Standard_Long_Long_Float;
+      end Find_Base_Type;
+
+   --  Start of processing for Floating_Point_Type_Declaration
 
    begin
-      if Nkind (C) = N_Range_Constraint then
-         return True;
+      Check_Restriction (No_Floating_Point, Def);
 
-      elsif Nkind (C) = N_Digits_Constraint then
-         return
-            Is_Decimal_Fixed_Point_Type (Entity (Subtype_Mark (N)))
-              or else
-            Present (Range_Constraint (C));
+      --  Create an implicit base type
 
-      elsif Nkind (C) = N_Delta_Constraint then
-         return Present (Range_Constraint (C));
+      Implicit_Base :=
+        Create_Itype (E_Floating_Point_Type, Parent (Def), T, 'B');
 
-      else
-         return False;
-      end if;
-   end Has_Range_Constraint;
+      --  Analyze and verify digits value
 
-   ------------------------
-   -- Inherit_Components --
-   ------------------------
+      Analyze_And_Resolve (Digs, Any_Integer);
+      Check_Digits_Expression (Digs);
+      Digs_Val := Expr_Value (Digs);
 
-   function Inherit_Components
-     (N             : Node_Id;
-      Parent_Base   : Entity_Id;
-      Derived_Base  : Entity_Id;
-      Is_Tagged     : Boolean;
-      Inherit_Discr : Boolean;
-      Discs         : Elist_Id) return Elist_Id
-   is
-      Assoc_List : constant Elist_Id := New_Elmt_List;
+      --  Process possible range spec and find correct type to derive from
 
-      procedure Inherit_Component
-        (Old_C          : Entity_Id;
-         Plain_Discrim  : Boolean := False;
-         Stored_Discrim : Boolean := False);
-      --  Inherits component Old_C from Parent_Base to the Derived_Base. If
-      --  Plain_Discrim is True, Old_C is a discriminant. If Stored_Discrim is
-      --  True, Old_C is a stored discriminant. If they are both false then
-      --  Old_C is a regular component.
+      Process_Real_Range_Specification (Def);
 
-      -----------------------
-      -- Inherit_Component --
-      -----------------------
+      --  Check that requested number of digits is not too high.
 
-      procedure Inherit_Component
-        (Old_C          : Entity_Id;
-         Plain_Discrim  : Boolean := False;
-         Stored_Discrim : Boolean := False)
-      is
-         procedure Set_Anonymous_Type (Id : Entity_Id);
-         --  Id denotes the entity of an access discriminant or anonymous
-         --  access component. Set the type of Id to either the same type of
-         --  Old_C or create a new one depending on whether the parent and
-         --  the child types are in the same scope.
+      if Digs_Val > Max_Digs_Val then
 
-         ------------------------
-         -- Set_Anonymous_Type --
-         ------------------------
+         --  The check for Max_Base_Digits may be somewhat expensive, as it
+         --  requires reading System, so only do it when necessary.
 
-         procedure Set_Anonymous_Type (Id : Entity_Id) is
-            Old_Typ : constant Entity_Id := Etype (Old_C);
+         declare
+            Max_Base_Digits : constant Uint :=
+                                Expr_Value
+                                  (Expression
+                                     (Parent (RTE (RE_Max_Base_Digits))));
 
          begin
-            if Scope (Parent_Base) = Scope (Derived_Base) then
-               Set_Etype (Id, Old_Typ);
+            if Digs_Val > Max_Base_Digits then
+               Error_Msg_Uint_1 := Max_Base_Digits;
+               Error_Msg_N ("digits value out of range, maximum is ^", Digs);
 
-            --  The parent and the derived type are in two different scopes.
-            --  Reuse the type of the original discriminant / component by
-            --  copying it in order to preserve all attributes.
+            elsif No (Real_Range_Specification (Def)) then
+               Error_Msg_Uint_1 := Max_Digs_Val;
+               Error_Msg_N ("types with more than ^ digits need range spec "
+                 & "(RM 3.5.7(6))", Digs);
+            end if;
+         end;
+      end if;
 
-            else
-               declare
-                  Typ : constant Entity_Id := New_Copy (Old_Typ);
+      --  Find a suitable type to derive from or complain and use a substitute
 
-               begin
-                  Set_Etype (Id, Typ);
+      Base_Typ := Find_Base_Type;
 
-                  --  Since we do not generate component declarations for
-                  --  inherited components, associate the itype with the
-                  --  derived type.
+      --  If there are bounds given in the declaration use them as the bounds
+      --  of the type, otherwise use the bounds of the predefined base type
+      --  that was chosen based on the Digits value.
 
-                  Set_Associated_Node_For_Itype (Typ, Parent (Derived_Base));
-                  Set_Scope                     (Typ, Derived_Base);
-               end;
-            end if;
-         end Set_Anonymous_Type;
+      if Present (Real_Range_Specification (Def)) then
+         Set_Scalar_Range (T, Real_Range_Specification (Def));
+         Set_Is_Constrained (T);
 
-         --  Local variables and constants
+         --  The bounds of this range must be converted to machine numbers
+         --  in accordance with RM 4.9(38).
 
-         New_C : constant Entity_Id := New_Copy (Old_C);
+         Bound := Type_Low_Bound (T);
 
-         Corr_Discrim : Entity_Id;
-         Discrim      : Entity_Id;
+         if Nkind (Bound) = N_Real_Literal then
+            Set_Realval
+              (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
+            Set_Is_Machine_Number (Bound);
+         end if;
 
-      --  Start of processing for Inherit_Component
+         Bound := Type_High_Bound (T);
 
-      begin
-         pragma Assert (not Is_Tagged or else not Stored_Discrim);
+         if Nkind (Bound) = N_Real_Literal then
+            Set_Realval
+              (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
+            Set_Is_Machine_Number (Bound);
+         end if;
 
-         Set_Parent (New_C, Parent (Old_C));
+      else
+         Set_Scalar_Range (T, Scalar_Range (Base_Typ));
+      end if;
 
-         --  Regular discriminants and components must be inserted in the scope
-         --  of the Derived_Base. Do it here.
+      --  Complete definition of implicit base and declared first subtype. The
+      --  inheritance of the rep item chain ensures that SPARK-related pragmas
+      --  are not clobbered when the floating point type acts as a full view of
+      --  a private type.
+
+      Set_Etype              (Implicit_Base,                 Base_Typ);
+      Set_Scalar_Range       (Implicit_Base, Scalar_Range   (Base_Typ));
+      Set_Size_Info          (Implicit_Base,                 Base_Typ);
+      Set_RM_Size            (Implicit_Base, RM_Size        (Base_Typ));
+      Set_First_Rep_Item     (Implicit_Base, First_Rep_Item (Base_Typ));
+      Set_Digits_Value       (Implicit_Base, Digits_Value   (Base_Typ));
+      Set_Float_Rep          (Implicit_Base, Float_Rep      (Base_Typ));
+
+      Set_Ekind              (T, E_Floating_Point_Subtype);
+      Set_Etype              (T,          Implicit_Base);
+      Set_Size_Info          (T,          Implicit_Base);
+      Set_RM_Size            (T, RM_Size (Implicit_Base));
+      Inherit_Rep_Item_Chain (T,          Implicit_Base);
+      Set_Digits_Value       (T, Digs_Val);
+   end Floating_Point_Type_Declaration;
 
-         if not Stored_Discrim then
-            Enter_Name (New_C);
-         end if;
+   ----------------------------
+   -- Get_Discriminant_Value --
+   ----------------------------
 
-         --  For tagged types the Original_Record_Component must point to
-         --  whatever this field was pointing to in the parent type. This has
-         --  already been achieved by the call to New_Copy above.
+   --  This is the situation:
 
-         if not Is_Tagged then
-            Set_Original_Record_Component (New_C, New_C);
-         end if;
+   --  There is a non-derived type
 
-         --  Set the proper type of an access discriminant
+   --       type T0 (Dx, Dy, Dz...)
 
-         if Ekind (New_C) = E_Discriminant
-           and then Ekind (Etype (New_C)) = E_Anonymous_Access_Type
-         then
-            Set_Anonymous_Type (New_C);
-         end if;
+   --  There are zero or more levels of derivation, with each derivation
+   --  either purely inheriting the discriminants, or defining its own.
 
-         --  If we have inherited a component then see if its Etype contains
-         --  references to Parent_Base discriminants. In this case, replace
-         --  these references with the constraints given in Discs. We do not
-         --  do this for the partial view of private types because this is
-         --  not needed (only the components of the full view will be used
-         --  for code generation) and cause problem. We also avoid this
-         --  transformation in some error situations.
+   --       type Ti      is new Ti-1
+   --  or
+   --       type Ti (Dw) is new Ti-1(Dw, 1, X+Y)
+   --  or
+   --       subtype Ti is ...
 
-         if Ekind (New_C) = E_Component then
+   --  The subtype issue is avoided by the use of Original_Record_Component,
+   --  and the fact that derived subtypes also derive the constraints.
 
-            --  Set the proper type of an anonymous access component
+   --  This chain leads back from
 
-            if Ekind (Etype (New_C)) = E_Anonymous_Access_Type then
-               Set_Anonymous_Type (New_C);
+   --       Typ_For_Constraint
 
-            elsif (Is_Private_Type (Derived_Base)
-                    and then not Is_Generic_Type (Derived_Base))
-              or else (Is_Empty_Elmt_List (Discs)
-                         and then not Expander_Active)
-            then
-               Set_Etype (New_C, Etype (Old_C));
+   --  Typ_For_Constraint has discriminants, and the value for each
+   --  discriminant is given by its corresponding Elmt of Constraints.
 
-            else
-               --  The current component introduces a circularity of the
-               --  following kind:
+   --  Discriminant is some discriminant in this hierarchy
 
-               --     limited with Pack_2;
-               --     package Pack_1 is
-               --        type T_1 is tagged record
-               --           Comp : access Pack_2.T_2;
-               --           ...
-               --        end record;
-               --     end Pack_1;
+   --  We need to return its value
 
-               --     with Pack_1;
-               --     package Pack_2 is
-               --        type T_2 is new Pack_1.T_1 with ...;
-               --     end Pack_2;
+   --  We do this by recursively searching each level, and looking for
+   --  Discriminant. Once we get to the bottom, we start backing up
+   --  returning the value for it which may in turn be a discriminant
+   --  further up, so on the backup we continue the substitution.
 
-               Set_Etype
-                 (New_C,
-                  Constrain_Component_Type
-                    (Old_C, Derived_Base, N, Parent_Base, Discs));
-            end if;
-         end if;
+   function Get_Discriminant_Value
+     (Discriminant       : Entity_Id;
+      Typ_For_Constraint : Entity_Id;
+      Constraint         : Elist_Id) return Node_Id
+   is
+      function Root_Corresponding_Discriminant
+        (Discr : Entity_Id) return Entity_Id;
+      --  Given a discriminant, traverse the chain of inherited discriminants
+      --  and return the topmost discriminant.
 
-         --  In derived tagged types it is illegal to reference a non
-         --  discriminant component in the parent type. To catch this, mark
-         --  these components with an Ekind of E_Void. This will be reset in
-         --  Record_Type_Definition after processing the record extension of
-         --  the derived type.
+      function Search_Derivation_Levels
+        (Ti                    : Entity_Id;
+         Discrim_Values        : Elist_Id;
+         Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id;
+      --  This is the routine that performs the recursive search of levels
+      --  as described above.
 
-         --  If the declaration is a private extension, there is no further
-         --  record extension to process, and the components retain their
-         --  current kind, because they are visible at this point.
+      -------------------------------------
+      -- Root_Corresponding_Discriminant --
+      -------------------------------------
 
-         if Is_Tagged and then Ekind (New_C) = E_Component
-           and then Nkind (N) /= N_Private_Extension_Declaration
-         then
-            Set_Ekind (New_C, E_Void);
-         end if;
+      function Root_Corresponding_Discriminant
+        (Discr : Entity_Id) return Entity_Id
+      is
+         D : Entity_Id;
+
+      begin
+         D := Discr;
+         while Present (Corresponding_Discriminant (D)) loop
+            D := Corresponding_Discriminant (D);
+         end loop;
+
+         return D;
+      end Root_Corresponding_Discriminant;
 
-         if Plain_Discrim then
-            Set_Corresponding_Discriminant (New_C, Old_C);
-            Build_Discriminal (New_C);
+      ------------------------------
+      -- Search_Derivation_Levels --
+      ------------------------------
 
-         --  If we are explicitly inheriting a stored discriminant it will be
-         --  completely hidden.
+      function Search_Derivation_Levels
+        (Ti                    : Entity_Id;
+         Discrim_Values        : Elist_Id;
+         Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id
+      is
+         Assoc          : Elmt_Id;
+         Disc           : Entity_Id;
+         Result         : Node_Or_Entity_Id;
+         Result_Entity  : Node_Id;
 
-         elsif Stored_Discrim then
-            Set_Corresponding_Discriminant (New_C, Empty);
-            Set_Discriminal (New_C, Empty);
-            Set_Is_Completely_Hidden (New_C);
+      begin
+         --  If inappropriate type, return Error, this happens only in
+         --  cascaded error situations, and we want to avoid a blow up.
 
-            --  Set the Original_Record_Component of each discriminant in the
-            --  derived base to point to the corresponding stored that we just
-            --  created.
+         if not Is_Composite_Type (Ti) or else Is_Array_Type (Ti) then
+            return Error;
+         end if;
 
-            Discrim := First_Discriminant (Derived_Base);
-            while Present (Discrim) loop
-               Corr_Discrim := Corresponding_Discriminant (Discrim);
+         --  Look deeper if possible. Use Stored_Constraints only for
+         --  untagged types. For tagged types use the given constraint.
+         --  This asymmetry needs explanation???
 
-               --  Corr_Discrim could be missing in an error situation
+         if not Stored_Discrim_Values
+           and then Present (Stored_Constraint (Ti))
+           and then not Is_Tagged_Type (Ti)
+         then
+            Result :=
+              Search_Derivation_Levels (Ti, Stored_Constraint (Ti), True);
+         else
+            declare
+               Td : constant Entity_Id := Etype (Ti);
 
-               if Present (Corr_Discrim)
-                 and then Original_Record_Component (Corr_Discrim) = Old_C
-               then
-                  Set_Original_Record_Component (Discrim, New_C);
+            begin
+               if Td = Ti then
+                  Result := Discriminant;
+
+               else
+                  if Present (Stored_Constraint (Ti)) then
+                     Result :=
+                        Search_Derivation_Levels
+                          (Td, Stored_Constraint (Ti), True);
+                  else
+                     Result :=
+                        Search_Derivation_Levels
+                          (Td, Discrim_Values, Stored_Discrim_Values);
+                  end if;
                end if;
+            end;
+         end if;
 
-               Next_Discriminant (Discrim);
-            end loop;
+         --  Extra underlying places to search, if not found above. For
+         --  concurrent types, the relevant discriminant appears in the
+         --  corresponding record. For a type derived from a private type
+         --  without discriminant, the full view inherits the discriminants
+         --  of the full view of the parent.
 
-            Append_Entity (New_C, Derived_Base);
-         end if;
+         if Result = Discriminant then
+            if Is_Concurrent_Type (Ti)
+              and then Present (Corresponding_Record_Type (Ti))
+            then
+               Result :=
+                 Search_Derivation_Levels (
+                   Corresponding_Record_Type (Ti),
+                   Discrim_Values,
+                   Stored_Discrim_Values);
 
-         if not Is_Tagged then
-            Append_Elmt (Old_C, Assoc_List);
-            Append_Elmt (New_C, Assoc_List);
+            elsif Is_Private_Type (Ti)
+              and then not Has_Discriminants (Ti)
+              and then Present (Full_View (Ti))
+              and then Etype (Full_View (Ti)) /= Ti
+            then
+               Result :=
+                 Search_Derivation_Levels (
+                   Full_View (Ti),
+                   Discrim_Values,
+                   Stored_Discrim_Values);
+            end if;
          end if;
-      end Inherit_Component;
 
-      --  Variables local to Inherit_Component
+         --  If Result is not a (reference to a) discriminant, return it,
+         --  otherwise set Result_Entity to the discriminant.
 
-      Loc : constant Source_Ptr := Sloc (N);
+         if Nkind (Result) = N_Defining_Identifier then
+            pragma Assert (Result = Discriminant);
+            Result_Entity := Result;
 
-      Parent_Discrim : Entity_Id;
-      Stored_Discrim : Entity_Id;
-      D              : Entity_Id;
-      Component      : Entity_Id;
+         else
+            if not Denotes_Discriminant (Result) then
+               return Result;
+            end if;
 
-   --  Start of processing for Inherit_Components
+            Result_Entity := Entity (Result);
+         end if;
 
-   begin
-      if not Is_Tagged then
-         Append_Elmt (Parent_Base,  Assoc_List);
-         Append_Elmt (Derived_Base, Assoc_List);
-      end if;
+         --  See if this level of derivation actually has discriminants because
+         --  tagged derivations can add them, hence the lower levels need not
+         --  have any.
 
-      --  Inherit parent discriminants if needed
+         if not Has_Discriminants (Ti) then
+            return Result;
+         end if;
 
-      if Inherit_Discr then
-         Parent_Discrim := First_Discriminant (Parent_Base);
-         while Present (Parent_Discrim) loop
-            Inherit_Component (Parent_Discrim, Plain_Discrim => True);
-            Next_Discriminant (Parent_Discrim);
-         end loop;
-      end if;
+         --  Scan Ti's discriminants for Result_Entity, and return its
+         --  corresponding value, if any.
 
-      --  Create explicit stored discrims for untagged types when necessary
+         Result_Entity := Original_Record_Component (Result_Entity);
 
-      if not Has_Unknown_Discriminants (Derived_Base)
-        and then Has_Discriminants (Parent_Base)
-        and then not Is_Tagged
-        and then
-          (not Inherit_Discr
-             or else First_Discriminant (Parent_Base) /=
-                     First_Stored_Discriminant (Parent_Base))
-      then
-         Stored_Discrim := First_Stored_Discriminant (Parent_Base);
-         while Present (Stored_Discrim) loop
-            Inherit_Component (Stored_Discrim, Stored_Discrim => True);
-            Next_Stored_Discriminant (Stored_Discrim);
-         end loop;
-      end if;
+         Assoc := First_Elmt (Discrim_Values);
 
-      --  See if we can apply the second transformation for derived types, as
-      --  explained in point 6. in the comments above Build_Derived_Record_Type
-      --  This is achieved by appending Derived_Base discriminants into Discs,
-      --  which has the side effect of returning a non empty Discs list to the
-      --  caller of Inherit_Components, which is what we want. This must be
-      --  done for private derived types if there are explicit stored
-      --  discriminants, to ensure that we can retrieve the values of the
-      --  constraints provided in the ancestors.
+         if Stored_Discrim_Values then
+            Disc := First_Stored_Discriminant (Ti);
+         else
+            Disc := First_Discriminant (Ti);
+         end if;
 
-      if Inherit_Discr
-        and then Is_Empty_Elmt_List (Discs)
-        and then Present (First_Discriminant (Derived_Base))
-        and then
-          (not Is_Private_Type (Derived_Base)
-             or else Is_Completely_Hidden
-               (First_Stored_Discriminant (Derived_Base))
-             or else Is_Generic_Type (Derived_Base))
-      then
-         D := First_Discriminant (Derived_Base);
-         while Present (D) loop
-            Append_Elmt (New_Occurrence_Of (D, Loc), Discs);
-            Next_Discriminant (D);
-         end loop;
-      end if;
+         while Present (Disc) loop
+            pragma Assert (Present (Assoc));
 
-      --  Finally, inherit non-discriminant components unless they are not
-      --  visible because defined or inherited from the full view of the
-      --  parent. Don't inherit the _parent field of the parent type.
+            if Original_Record_Component (Disc) = Result_Entity then
+               return Node (Assoc);
+            end if;
 
-      Component := First_Entity (Parent_Base);
-      while Present (Component) loop
+            Next_Elmt (Assoc);
 
-         --  Ada 2005 (AI-251): Do not inherit components associated with
-         --  secondary tags of the parent.
+            if Stored_Discrim_Values then
+               Next_Stored_Discriminant (Disc);
+            else
+               Next_Discriminant (Disc);
+            end if;
+         end loop;
 
-         if Ekind (Component) = E_Component
-           and then Present (Related_Type (Component))
-         then
-            null;
+         --  Could not find it
 
-         elsif Ekind (Component) /= E_Component
-           or else Chars (Component) = Name_uParent
-         then
-            null;
+         return Result;
+      end Search_Derivation_Levels;
 
-         --  If the derived type is within the parent type's declarative
-         --  region, then the components can still be inherited even though
-         --  they aren't visible at this point. This can occur for cases
-         --  such as within public child units where the components must
-         --  become visible upon entering the child unit's private part.
+      --  Local Variables
 
-         elsif not Is_Visible_Component (Component)
-           and then not In_Open_Scopes (Scope (Parent_Base))
-         then
-            null;
+      Result : Node_Or_Entity_Id;
 
-         elsif Ekind_In (Derived_Base, E_Private_Type,
-                                       E_Limited_Private_Type)
-         then
-            null;
+   --  Start of processing for Get_Discriminant_Value
 
-         else
-            Inherit_Component (Component);
-         end if;
+   begin
+      --  ??? This routine is a gigantic mess and will be deleted. For the
+      --  time being just test for the trivial case before calling recurse.
 
-         Next_Entity (Component);
-      end loop;
+      if Base_Type (Scope (Discriminant)) = Base_Type (Typ_For_Constraint) then
+         declare
+            D : Entity_Id;
+            E : Elmt_Id;
 
-      --  For tagged derived types, inherited discriminants cannot be used in
-      --  component declarations of the record extension part. To achieve this
-      --  we mark the inherited discriminants as not visible.
+         begin
+            D := First_Discriminant (Typ_For_Constraint);
+            E := First_Elmt (Constraint);
+            while Present (D) loop
+               if Chars (D) = Chars (Discriminant) then
+                  return Node (E);
+               end if;
 
-      if Is_Tagged and then Inherit_Discr then
-         D := First_Discriminant (Derived_Base);
-         while Present (D) loop
-            Set_Is_Immediately_Visible (D, False);
-            Next_Discriminant (D);
-         end loop;
+               Next_Discriminant (D);
+               Next_Elmt (E);
+            end loop;
+         end;
       end if;
 
-      return Assoc_List;
-   end Inherit_Components;
-
-   -----------------------------
-   -- Inherit_Predicate_Flags --
-   -----------------------------
+      Result := Search_Derivation_Levels
+        (Typ_For_Constraint, Constraint, False);
 
-   procedure Inherit_Predicate_Flags (Subt, Par : Entity_Id) is
-   begin
-      Set_Has_Predicates (Subt, Has_Predicates (Par));
-      Set_Has_Static_Predicate_Aspect
-        (Subt, Has_Static_Predicate_Aspect (Par));
-      Set_Has_Dynamic_Predicate_Aspect
-        (Subt, Has_Dynamic_Predicate_Aspect (Par));
-   end Inherit_Predicate_Flags;
+      --  ??? hack to disappear when this routine is gone
 
-   -----------------------
-   -- Is_Null_Extension --
-   -----------------------
+      if Nkind (Result) = N_Defining_Identifier then
+         declare
+            D : Entity_Id;
+            E : Elmt_Id;
 
-   function Is_Null_Extension (T : Entity_Id) return Boolean is
-      Type_Decl : constant Node_Id := Parent (Base_Type (T));
-      Comp_List : Node_Id;
-      Comp      : Node_Id;
+         begin
+            D := First_Discriminant (Typ_For_Constraint);
+            E := First_Elmt (Constraint);
+            while Present (D) loop
+               if Root_Corresponding_Discriminant (D) = Discriminant then
+                  return Node (E);
+               end if;
 
-   begin
-      if Nkind (Type_Decl) /= N_Full_Type_Declaration
-        or else not Is_Tagged_Type (T)
-        or else Nkind (Type_Definition (Type_Decl)) /=
-                                              N_Derived_Type_Definition
-        or else No (Record_Extension_Part (Type_Definition (Type_Decl)))
-      then
-         return False;
+               Next_Discriminant (D);
+               Next_Elmt (E);
+            end loop;
+         end;
       end if;
 
-      Comp_List :=
-        Component_List (Record_Extension_Part (Type_Definition (Type_Decl)));
+      pragma Assert (Nkind (Result) /= N_Defining_Identifier);
+      return Result;
+   end Get_Discriminant_Value;
 
-      if Present (Discriminant_Specifications (Type_Decl)) then
-         return False;
+   --------------------------
+   -- Has_Range_Constraint --
+   --------------------------
 
-      elsif Present (Comp_List)
-        and then Is_Non_Empty_List (Component_Items (Comp_List))
-      then
-         Comp := First (Component_Items (Comp_List));
+   function Has_Range_Constraint (N : Node_Id) return Boolean is
+      C : constant Node_Id := Constraint (N);
 
-         --  Only user-defined components are relevant. The component list
-         --  may also contain a parent component and internal components
-         --  corresponding to secondary tags, but these do not determine
-         --  whether this is a null extension.
+   begin
+      if Nkind (C) = N_Range_Constraint then
+         return True;
 
-         while Present (Comp) loop
-            if Comes_From_Source (Comp) then
-               return False;
-            end if;
+      elsif Nkind (C) = N_Digits_Constraint then
+         return
+            Is_Decimal_Fixed_Point_Type (Entity (Subtype_Mark (N)))
+              or else Present (Range_Constraint (C));
 
-            Next (Comp);
-         end loop;
+      elsif Nkind (C) = N_Delta_Constraint then
+         return Present (Range_Constraint (C));
 
-         return True;
       else
-         return True;
+         return False;
       end if;
-   end Is_Null_Extension;
+   end Has_Range_Constraint;
 
-   ------------------------------
-   -- Is_Valid_Constraint_Kind --
-   ------------------------------
+   ------------------------
+   -- Inherit_Components --
+   ------------------------
 
-   function Is_Valid_Constraint_Kind
-     (T_Kind          : Type_Kind;
-      Constraint_Kind : Node_Kind) return Boolean
+   function Inherit_Components
+     (N             : Node_Id;
+      Parent_Base   : Entity_Id;
+      Derived_Base  : Entity_Id;
+      Is_Tagged     : Boolean;
+      Inherit_Discr : Boolean;
+      Discs         : Elist_Id) return Elist_Id
    is
-   begin
-      case T_Kind is
-         when Enumeration_Kind |
-              Integer_Kind =>
-            return Constraint_Kind = N_Range_Constraint;
+      Assoc_List : constant Elist_Id := New_Elmt_List;
 
-         when Decimal_Fixed_Point_Kind =>
-            return Nkind_In (Constraint_Kind, N_Digits_Constraint,
-                                              N_Range_Constraint);
+      procedure Inherit_Component
+        (Old_C          : Entity_Id;
+         Plain_Discrim  : Boolean := False;
+         Stored_Discrim : Boolean := False);
+      --  Inherits component Old_C from Parent_Base to the Derived_Base. If
+      --  Plain_Discrim is True, Old_C is a discriminant. If Stored_Discrim is
+      --  True, Old_C is a stored discriminant. If they are both false then
+      --  Old_C is a regular component.
 
-         when Ordinary_Fixed_Point_Kind =>
-            return Nkind_In (Constraint_Kind, N_Delta_Constraint,
-                                              N_Range_Constraint);
+      -----------------------
+      -- Inherit_Component --
+      -----------------------
 
-         when Float_Kind =>
-            return Nkind_In (Constraint_Kind, N_Digits_Constraint,
-                                              N_Range_Constraint);
+      procedure Inherit_Component
+        (Old_C          : Entity_Id;
+         Plain_Discrim  : Boolean := False;
+         Stored_Discrim : Boolean := False)
+      is
+         procedure Set_Anonymous_Type (Id : Entity_Id);
+         --  Id denotes the entity of an access discriminant or anonymous
+         --  access component. Set the type of Id to either the same type of
+         --  Old_C or create a new one depending on whether the parent and
+         --  the child types are in the same scope.
 
-         when Access_Kind       |
-              Array_Kind        |
-              E_Record_Type     |
-              E_Record_Subtype  |
-              Class_Wide_Kind   |
-              E_Incomplete_Type |
-              Private_Kind      |
-              Concurrent_Kind  =>
-            return Constraint_Kind = N_Index_Or_Discriminant_Constraint;
+         ------------------------
+         -- Set_Anonymous_Type --
+         ------------------------
 
-         when others =>
-            return True; -- Error will be detected later
-      end case;
-   end Is_Valid_Constraint_Kind;
+         procedure Set_Anonymous_Type (Id : Entity_Id) is
+            Old_Typ : constant Entity_Id := Etype (Old_C);
 
-   --------------------------
-   -- Is_Visible_Component --
-   --------------------------
+         begin
+            if Scope (Parent_Base) = Scope (Derived_Base) then
+               Set_Etype (Id, Old_Typ);
 
-   function Is_Visible_Component
-     (C : Entity_Id;
-      N : Node_Id := Empty) return Boolean
-   is
-      Original_Comp  : Entity_Id := Empty;
-      Original_Scope : Entity_Id;
-      Type_Scope     : Entity_Id;
+            --  The parent and the derived type are in two different scopes.
+            --  Reuse the type of the original discriminant / component by
+            --  copying it in order to preserve all attributes.
 
-      function Is_Local_Type (Typ : Entity_Id) return Boolean;
-      --  Check whether parent type of inherited component is declared locally,
-      --  possibly within a nested package or instance. The current scope is
-      --  the derived record itself.
+            else
+               declare
+                  Typ : constant Entity_Id := New_Copy (Old_Typ);
 
-      -------------------
-      -- Is_Local_Type --
-      -------------------
+               begin
+                  Set_Etype (Id, Typ);
 
-      function Is_Local_Type (Typ : Entity_Id) return Boolean is
-         Scop : Entity_Id;
+                  --  Since we do not generate component declarations for
+                  --  inherited components, associate the itype with the
+                  --  derived type.
 
-      begin
-         Scop := Scope (Typ);
-         while Present (Scop)
-           and then Scop /= Standard_Standard
-         loop
-            if Scop = Scope (Current_Scope) then
-               return True;
+                  Set_Associated_Node_For_Itype (Typ, Parent (Derived_Base));
+                  Set_Scope                     (Typ, Derived_Base);
+               end;
             end if;
+         end Set_Anonymous_Type;
 
-            Scop := Scope (Scop);
-         end loop;
-
-         return False;
-      end Is_Local_Type;
+         --  Local variables and constants
 
-   --  Start of processing for Is_Visible_Component
+         New_C : constant Entity_Id := New_Copy (Old_C);
 
-   begin
-      if Ekind_In (C, E_Component, E_Discriminant) then
-         Original_Comp := Original_Record_Component (C);
-      end if;
+         Corr_Discrim : Entity_Id;
+         Discrim      : Entity_Id;
 
-      if No (Original_Comp) then
+      --  Start of processing for Inherit_Component
 
-         --  Premature usage, or previous error
+      begin
+         pragma Assert (not Is_Tagged or not Stored_Discrim);
 
-         return False;
+         Set_Parent (New_C, Parent (Old_C));
 
-      else
-         Original_Scope := Scope (Original_Comp);
-         Type_Scope     := Scope (Base_Type (Scope (C)));
-      end if;
+         --  Regular discriminants and components must be inserted in the scope
+         --  of the Derived_Base. Do it here.
 
-      --  This test only concerns tagged types
+         if not Stored_Discrim then
+            Enter_Name (New_C);
+         end if;
 
-      if not Is_Tagged_Type (Original_Scope) then
-         return True;
+         --  For tagged types the Original_Record_Component must point to
+         --  whatever this field was pointing to in the parent type. This has
+         --  already been achieved by the call to New_Copy above.
 
-      --  If it is _Parent or _Tag, there is no visibility issue
+         if not Is_Tagged then
+            Set_Original_Record_Component (New_C, New_C);
+         end if;
 
-      elsif not Comes_From_Source (Original_Comp) then
-         return True;
+         --  Set the proper type of an access discriminant
 
-      --  Discriminants are visible unless the (private) type has unknown
-      --  discriminants. If the discriminant reference is inserted for a
-      --  discriminant check on a full view it is also visible.
+         if Ekind (New_C) = E_Discriminant
+           and then Ekind (Etype (New_C)) = E_Anonymous_Access_Type
+         then
+            Set_Anonymous_Type (New_C);
+         end if;
 
-      elsif Ekind (Original_Comp) = E_Discriminant
-        and then
-          (not Has_Unknown_Discriminants (Original_Scope)
-            or else (Present (N)
-                      and then Nkind (N) = N_Selected_Component
-                      and then Nkind (Prefix (N)) = N_Type_Conversion
-                      and then not Comes_From_Source (Prefix (N))))
-      then
-         return True;
+         --  If we have inherited a component then see if its Etype contains
+         --  references to Parent_Base discriminants. In this case, replace
+         --  these references with the constraints given in Discs. We do not
+         --  do this for the partial view of private types because this is
+         --  not needed (only the components of the full view will be used
+         --  for code generation) and cause problem. We also avoid this
+         --  transformation in some error situations.
 
-      --  In the body of an instantiation, no need to check for the visibility
-      --  of a component.
+         if Ekind (New_C) = E_Component then
 
-      elsif In_Instance_Body then
-         return True;
+            --  Set the proper type of an anonymous access component
 
-      --  If the component has been declared in an ancestor which is currently
-      --  a private type, then it is not visible. The same applies if the
-      --  component's containing type is not in an open scope and the original
-      --  component's enclosing type is a visible full view of a private type
-      --  (which can occur in cases where an attempt is being made to reference
-      --  a component in a sibling package that is inherited from a visible
-      --  component of a type in an ancestor package; the component in the
-      --  sibling package should not be visible even though the component it
-      --  inherited from is visible). This does not apply however in the case
-      --  where the scope of the type is a private child unit, or when the
-      --  parent comes from a local package in which the ancestor is currently
-      --  visible. The latter suppression of visibility is needed for cases
-      --  that are tested in B730006.
+            if Ekind (Etype (New_C)) = E_Anonymous_Access_Type then
+               Set_Anonymous_Type (New_C);
 
-      elsif Is_Private_Type (Original_Scope)
-        or else
-          (not Is_Private_Descendant (Type_Scope)
-            and then not In_Open_Scopes (Type_Scope)
-            and then Has_Private_Declaration (Original_Scope))
-      then
-         --  If the type derives from an entity in a formal package, there
-         --  are no additional visible components.
+            elsif (Is_Private_Type (Derived_Base)
+                    and then not Is_Generic_Type (Derived_Base))
+              or else (Is_Empty_Elmt_List (Discs)
+                        and then not Expander_Active)
+            then
+               Set_Etype (New_C, Etype (Old_C));
 
-         if Nkind (Original_Node (Unit_Declaration_Node (Type_Scope))) =
-            N_Formal_Package_Declaration
-         then
-            return False;
+            else
+               --  The current component introduces a circularity of the
+               --  following kind:
 
-         --  if we are not in the private part of the current package, there
-         --  are no additional visible components.
+               --     limited with Pack_2;
+               --     package Pack_1 is
+               --        type T_1 is tagged record
+               --           Comp : access Pack_2.T_2;
+               --           ...
+               --        end record;
+               --     end Pack_1;
 
-         elsif Ekind (Scope (Current_Scope)) = E_Package
-           and then not In_Private_Part (Scope (Current_Scope))
-         then
-            return False;
-         else
-            return
-              Is_Child_Unit (Cunit_Entity (Current_Sem_Unit))
-                and then In_Open_Scopes (Scope (Original_Scope))
-                and then Is_Local_Type (Type_Scope);
+               --     with Pack_1;
+               --     package Pack_2 is
+               --        type T_2 is new Pack_1.T_1 with ...;
+               --     end Pack_2;
+
+               Set_Etype
+                 (New_C,
+                  Constrain_Component_Type
+                    (Old_C, Derived_Base, N, Parent_Base, Discs));
+            end if;
          end if;
 
-      --  There is another weird way in which a component may be invisible when
-      --  the private and the full view are not derived from the same ancestor.
-      --  Here is an example :
+         --  In derived tagged types it is illegal to reference a non
+         --  discriminant component in the parent type. To catch this, mark
+         --  these components with an Ekind of E_Void. This will be reset in
+         --  Record_Type_Definition after processing the record extension of
+         --  the derived type.
 
-      --       type A1 is tagged      record F1 : integer; end record;
-      --       type A2 is new A1 with record F2 : integer; end record;
-      --       type T is new A1 with private;
-      --     private
-      --       type T is new A2 with null record;
+         --  If the declaration is a private extension, there is no further
+         --  record extension to process, and the components retain their
+         --  current kind, because they are visible at this point.
 
-      --  In this case, the full view of T inherits F1 and F2 but the private
-      --  view inherits only F1
+         if Is_Tagged and then Ekind (New_C) = E_Component
+           and then Nkind (N) /= N_Private_Extension_Declaration
+         then
+            Set_Ekind (New_C, E_Void);
+         end if;
 
-      else
-         declare
-            Ancestor : Entity_Id := Scope (C);
+         if Plain_Discrim then
+            Set_Corresponding_Discriminant (New_C, Old_C);
+            Build_Discriminal (New_C);
 
-         begin
-            loop
-               if Ancestor = Original_Scope then
-                  return True;
-               elsif Ancestor = Etype (Ancestor) then
-                  return False;
-               end if;
+         --  If we are explicitly inheriting a stored discriminant it will be
+         --  completely hidden.
 
-               Ancestor := Etype (Ancestor);
-            end loop;
-         end;
-      end if;
-   end Is_Visible_Component;
+         elsif Stored_Discrim then
+            Set_Corresponding_Discriminant (New_C, Empty);
+            Set_Discriminal (New_C, Empty);
+            Set_Is_Completely_Hidden (New_C);
 
-   --------------------------
-   -- Make_Class_Wide_Type --
-   --------------------------
+            --  Set the Original_Record_Component of each discriminant in the
+            --  derived base to point to the corresponding stored that we just
+            --  created.
 
-   procedure Make_Class_Wide_Type (T : Entity_Id) is
-      CW_Type : Entity_Id;
-      CW_Name : Name_Id;
-      Next_E  : Entity_Id;
+            Discrim := First_Discriminant (Derived_Base);
+            while Present (Discrim) loop
+               Corr_Discrim := Corresponding_Discriminant (Discrim);
 
-   begin
-      if Present (Class_Wide_Type (T)) then
+               --  Corr_Discrim could be missing in an error situation
 
-         --  The class-wide type is a partially decorated entity created for a
-         --  unanalyzed tagged type referenced through a limited with clause.
-         --  When the tagged type is analyzed, its class-wide type needs to be
-         --  redecorated. Note that we reuse the entity created by Decorate_
-         --  Tagged_Type in order to preserve all links.
+               if Present (Corr_Discrim)
+                 and then Original_Record_Component (Corr_Discrim) = Old_C
+               then
+                  Set_Original_Record_Component (Discrim, New_C);
+               end if;
 
-         if Materialize_Entity (Class_Wide_Type (T)) then
-            CW_Type := Class_Wide_Type (T);
-            Set_Materialize_Entity (CW_Type, False);
+               Next_Discriminant (Discrim);
+            end loop;
 
-         --  The class wide type can have been defined by the partial view, in
-         --  which case everything is already done.
+            Append_Entity (New_C, Derived_Base);
+         end if;
 
-         else
-            return;
+         if not Is_Tagged then
+            Append_Elmt (Old_C, Assoc_List);
+            Append_Elmt (New_C, Assoc_List);
          end if;
+      end Inherit_Component;
 
-      --  Default case, we need to create a new class-wide type
+      --  Variables local to Inherit_Component
 
-      else
-         CW_Type :=
-           New_External_Entity (E_Void, Scope (T), Sloc (T), T, 'C', 0, 'T');
-      end if;
+      Loc : constant Source_Ptr := Sloc (N);
 
-      --  Inherit root type characteristics
+      Parent_Discrim : Entity_Id;
+      Stored_Discrim : Entity_Id;
+      D              : Entity_Id;
+      Component      : Entity_Id;
 
-      CW_Name := Chars (CW_Type);
-      Next_E  := Next_Entity (CW_Type);
-      Copy_Node (T, CW_Type);
-      Set_Comes_From_Source (CW_Type, False);
-      Set_Chars (CW_Type, CW_Name);
-      Set_Parent (CW_Type, Parent (T));
-      Set_Next_Entity (CW_Type, Next_E);
+   --  Start of processing for Inherit_Components
 
-      --  Ensure we have a new freeze node for the class-wide type. The partial
-      --  view may have freeze action of its own, requiring a proper freeze
-      --  node, and the same freeze node cannot be shared between the two
-      --  types.
+   begin
+      if not Is_Tagged then
+         Append_Elmt (Parent_Base,  Assoc_List);
+         Append_Elmt (Derived_Base, Assoc_List);
+      end if;
 
-      Set_Has_Delayed_Freeze (CW_Type);
-      Set_Freeze_Node (CW_Type, Empty);
+      --  Inherit parent discriminants if needed
 
-      --  Customize the class-wide type: It has no prim. op., it cannot be
-      --  abstract and its Etype points back to the specific root type.
+      if Inherit_Discr then
+         Parent_Discrim := First_Discriminant (Parent_Base);
+         while Present (Parent_Discrim) loop
+            Inherit_Component (Parent_Discrim, Plain_Discrim => True);
+            Next_Discriminant (Parent_Discrim);
+         end loop;
+      end if;
 
-      Set_Ekind                       (CW_Type, E_Class_Wide_Type);
-      Set_Is_Tagged_Type              (CW_Type, True);
-      Set_Direct_Primitive_Operations (CW_Type, New_Elmt_List);
-      Set_Is_Abstract_Type            (CW_Type, False);
-      Set_Is_Constrained              (CW_Type, False);
-      Set_Is_First_Subtype            (CW_Type, Is_First_Subtype (T));
-      Set_Default_SSO                 (CW_Type);
+      --  Create explicit stored discrims for untagged types when necessary
 
-      if Ekind (T) = E_Class_Wide_Subtype then
-         Set_Etype             (CW_Type, Etype (Base_Type (T)));
-      else
-         Set_Etype             (CW_Type, T);
+      if not Has_Unknown_Discriminants (Derived_Base)
+        and then Has_Discriminants (Parent_Base)
+        and then not Is_Tagged
+        and then
+          (not Inherit_Discr
+            or else First_Discriminant (Parent_Base) /=
+                    First_Stored_Discriminant (Parent_Base))
+      then
+         Stored_Discrim := First_Stored_Discriminant (Parent_Base);
+         while Present (Stored_Discrim) loop
+            Inherit_Component (Stored_Discrim, Stored_Discrim => True);
+            Next_Stored_Discriminant (Stored_Discrim);
+         end loop;
       end if;
 
-      --  If this is the class_wide type of a constrained subtype, it does
-      --  not have discriminants.
-
-      Set_Has_Discriminants (CW_Type,
-        Has_Discriminants (T) and then not Is_Constrained (T));
+      --  See if we can apply the second transformation for derived types, as
+      --  explained in point 6. in the comments above Build_Derived_Record_Type
+      --  This is achieved by appending Derived_Base discriminants into Discs,
+      --  which has the side effect of returning a non empty Discs list to the
+      --  caller of Inherit_Components, which is what we want. This must be
+      --  done for private derived types if there are explicit stored
+      --  discriminants, to ensure that we can retrieve the values of the
+      --  constraints provided in the ancestors.
 
-      Set_Has_Unknown_Discriminants (CW_Type, True);
-      Set_Class_Wide_Type (T, CW_Type);
-      Set_Equivalent_Type (CW_Type, Empty);
+      if Inherit_Discr
+        and then Is_Empty_Elmt_List (Discs)
+        and then Present (First_Discriminant (Derived_Base))
+        and then
+          (not Is_Private_Type (Derived_Base)
+            or else Is_Completely_Hidden
+                      (First_Stored_Discriminant (Derived_Base))
+            or else Is_Generic_Type (Derived_Base))
+      then
+         D := First_Discriminant (Derived_Base);
+         while Present (D) loop
+            Append_Elmt (New_Occurrence_Of (D, Loc), Discs);
+            Next_Discriminant (D);
+         end loop;
+      end if;
 
-      --  The class-wide type of a class-wide type is itself (RM 3.9(14))
+      --  Finally, inherit non-discriminant components unless they are not
+      --  visible because defined or inherited from the full view of the
+      --  parent. Don't inherit the _parent field of the parent type.
 
-      Set_Class_Wide_Type (CW_Type, CW_Type);
-   end Make_Class_Wide_Type;
+      Component := First_Entity (Parent_Base);
+      while Present (Component) loop
 
-   ----------------
-   -- Make_Index --
-   ----------------
+         --  Ada 2005 (AI-251): Do not inherit components associated with
+         --  secondary tags of the parent.
 
-   procedure Make_Index
-     (N            : Node_Id;
-      Related_Nod  : Node_Id;
-      Related_Id   : Entity_Id := Empty;
-      Suffix_Index : Nat       := 1;
-      In_Iter_Schm : Boolean   := False)
-   is
-      R      : Node_Id;
-      T      : Entity_Id;
-      Def_Id : Entity_Id := Empty;
-      Found  : Boolean := False;
+         if Ekind (Component) = E_Component
+           and then Present (Related_Type (Component))
+         then
+            null;
 
-   begin
-      --  For a discrete range used in a constrained array definition and
-      --  defined by a range, an implicit conversion to the predefined type
-      --  INTEGER is assumed if each bound is either a numeric literal, a named
-      --  number, or an attribute, and the type of both bounds (prior to the
-      --  implicit conversion) is the type universal_integer. Otherwise, both
-      --  bounds must be of the same discrete type, other than universal
-      --  integer; this type must be determinable independently of the
-      --  context, but using the fact that the type must be discrete and that
-      --  both bounds must have the same type.
+         elsif Ekind (Component) /= E_Component
+           or else Chars (Component) = Name_uParent
+         then
+            null;
 
-      --  Character literals also have a universal type in the absence of
-      --  of additional context,  and are resolved to Standard_Character.
+         --  If the derived type is within the parent type's declarative
+         --  region, then the components can still be inherited even though
+         --  they aren't visible at this point. This can occur for cases
+         --  such as within public child units where the components must
+         --  become visible upon entering the child unit's private part.
 
-      if Nkind (N) = N_Range then
+         elsif not Is_Visible_Component (Component)
+           and then not In_Open_Scopes (Scope (Parent_Base))
+         then
+            null;
 
-         --  The index is given by a range constraint. The bounds are known
-         --  to be of a consistent type.
+         elsif Ekind_In (Derived_Base, E_Private_Type,
+                                       E_Limited_Private_Type)
+         then
+            null;
 
-         if not Is_Overloaded (N) then
-            T := Etype (N);
+         else
+            Inherit_Component (Component);
+         end if;
 
-            --  For universal bounds, choose the specific predefined type
+         Next_Entity (Component);
+      end loop;
 
-            if T = Universal_Integer then
-               T := Standard_Integer;
+      --  For tagged derived types, inherited discriminants cannot be used in
+      --  component declarations of the record extension part. To achieve this
+      --  we mark the inherited discriminants as not visible.
 
-            elsif T = Any_Character then
-               Ambiguous_Character (Low_Bound (N));
+      if Is_Tagged and then Inherit_Discr then
+         D := First_Discriminant (Derived_Base);
+         while Present (D) loop
+            Set_Is_Immediately_Visible (D, False);
+            Next_Discriminant (D);
+         end loop;
+      end if;
 
-               T := Standard_Character;
-            end if;
+      return Assoc_List;
+   end Inherit_Components;
 
-         --  The node may be overloaded because some user-defined operators
-         --  are available, but if a universal interpretation exists it is
-         --  also the selected one.
+   -----------------------------
+   -- Inherit_Predicate_Flags --
+   -----------------------------
 
-         elsif Universal_Interpretation (N) = Universal_Integer then
-            T := Standard_Integer;
+   procedure Inherit_Predicate_Flags (Subt, Par : Entity_Id) is
+   begin
+      Set_Has_Predicates (Subt, Has_Predicates (Par));
+      Set_Has_Static_Predicate_Aspect
+        (Subt, Has_Static_Predicate_Aspect (Par));
+      Set_Has_Dynamic_Predicate_Aspect
+        (Subt, Has_Dynamic_Predicate_Aspect (Par));
+   end Inherit_Predicate_Flags;
 
-         else
-            T := Any_Type;
+   ----------------------
+   -- Is_EVF_Procedure --
+   ----------------------
 
-            declare
-               Ind : Interp_Index;
-               It  : Interp;
+   function Is_EVF_Procedure (Subp : Entity_Id) return Boolean is
+      Formal : Entity_Id;
 
-            begin
-               Get_First_Interp (N, Ind, It);
-               while Present (It.Typ) loop
-                  if Is_Discrete_Type (It.Typ) then
+   begin
+      --  Examine the formals of an Extensions_Visible False procedure looking
+      --  for a controlling OUT parameter.
 
-                     if Found
-                       and then not Covers (It.Typ, T)
-                       and then not Covers (T, It.Typ)
-                     then
-                        Error_Msg_N ("ambiguous bounds in discrete range", N);
-                        exit;
-                     else
-                        T := It.Typ;
-                        Found := True;
-                     end if;
-                  end if;
+      if Ekind (Subp) = E_Procedure
+        and then Extensions_Visible_Status (Subp) = Extensions_Visible_False
+      then
+         Formal := First_Formal (Subp);
+         while Present (Formal) loop
+            if Ekind (Formal) = E_Out_Parameter
+              and then Is_Controlling_Formal (Formal)
+            then
+               return True;
+            end if;
 
-                  Get_Next_Interp (Ind, It);
-               end loop;
+            Next_Formal (Formal);
+         end loop;
+      end if;
 
-               if T = Any_Type then
-                  Error_Msg_N ("discrete type required for range", N);
-                  Set_Etype (N, Any_Type);
-                  return;
+      return False;
+   end Is_EVF_Procedure;
 
-               elsif T = Universal_Integer then
-                  T := Standard_Integer;
-               end if;
-            end;
-         end if;
+   -----------------------
+   -- Is_Null_Extension --
+   -----------------------
 
-         if not Is_Discrete_Type (T) then
-            Error_Msg_N ("discrete type required for range", N);
-            Set_Etype (N, Any_Type);
-            return;
-         end if;
+   function Is_Null_Extension (T : Entity_Id) return Boolean is
+      Type_Decl : constant Node_Id := Parent (Base_Type (T));
+      Comp_List : Node_Id;
+      Comp      : Node_Id;
 
-         if Nkind (Low_Bound (N)) = N_Attribute_Reference
-           and then Attribute_Name (Low_Bound (N)) = Name_First
-           and then Is_Entity_Name (Prefix (Low_Bound (N)))
-           and then Is_Type (Entity (Prefix (Low_Bound (N))))
-           and then Is_Discrete_Type (Entity (Prefix (Low_Bound (N))))
-         then
-            --  The type of the index will be the type of the prefix, as long
-            --  as the upper bound is 'Last of the same type.
+   begin
+      if Nkind (Type_Decl) /= N_Full_Type_Declaration
+        or else not Is_Tagged_Type (T)
+        or else Nkind (Type_Definition (Type_Decl)) /=
+                                              N_Derived_Type_Definition
+        or else No (Record_Extension_Part (Type_Definition (Type_Decl)))
+      then
+         return False;
+      end if;
 
-            Def_Id := Entity (Prefix (Low_Bound (N)));
+      Comp_List :=
+        Component_List (Record_Extension_Part (Type_Definition (Type_Decl)));
 
-            if Nkind (High_Bound (N)) /= N_Attribute_Reference
-              or else Attribute_Name (High_Bound (N)) /= Name_Last
-              or else not Is_Entity_Name (Prefix (High_Bound (N)))
-              or else Entity (Prefix (High_Bound (N))) /= Def_Id
-            then
-               Def_Id := Empty;
-            end if;
-         end if;
+      if Present (Discriminant_Specifications (Type_Decl)) then
+         return False;
 
-         R := N;
-         Process_Range_Expr_In_Decl (R, T, In_Iter_Schm => In_Iter_Schm);
+      elsif Present (Comp_List)
+        and then Is_Non_Empty_List (Component_Items (Comp_List))
+      then
+         Comp := First (Component_Items (Comp_List));
 
-      elsif Nkind (N) = N_Subtype_Indication then
+         --  Only user-defined components are relevant. The component list
+         --  may also contain a parent component and internal components
+         --  corresponding to secondary tags, but these do not determine
+         --  whether this is a null extension.
 
-         --  The index is given by a subtype with a range constraint
+         while Present (Comp) loop
+            if Comes_From_Source (Comp) then
+               return False;
+            end if;
 
-         T :=  Base_Type (Entity (Subtype_Mark (N)));
+            Next (Comp);
+         end loop;
 
-         if not Is_Discrete_Type (T) then
-            Error_Msg_N ("discrete type required for range", N);
-            Set_Etype (N, Any_Type);
-            return;
-         end if;
+         return True;
 
-         R := Range_Expression (Constraint (N));
+      else
+         return True;
+      end if;
+   end Is_Null_Extension;
 
-         Resolve (R, T);
-         Process_Range_Expr_In_Decl
-           (R, Entity (Subtype_Mark (N)), In_Iter_Schm => In_Iter_Schm);
+   ------------------------------
+   -- Is_Valid_Constraint_Kind --
+   ------------------------------
 
-      elsif Nkind (N) = N_Attribute_Reference then
+   function Is_Valid_Constraint_Kind
+     (T_Kind          : Type_Kind;
+      Constraint_Kind : Node_Kind) return Boolean
+   is
+   begin
+      case T_Kind is
+         when Enumeration_Kind |
+              Integer_Kind =>
+            return Constraint_Kind = N_Range_Constraint;
 
-         --  Catch beginner's error (use of attribute other than 'Range)
+         when Decimal_Fixed_Point_Kind =>
+            return Nkind_In (Constraint_Kind, N_Digits_Constraint,
+                                              N_Range_Constraint);
 
-         if Attribute_Name (N) /= Name_Range then
-            Error_Msg_N ("expect attribute ''Range", N);
-            Set_Etype (N, Any_Type);
-            return;
-         end if;
+         when Ordinary_Fixed_Point_Kind =>
+            return Nkind_In (Constraint_Kind, N_Delta_Constraint,
+                                              N_Range_Constraint);
 
-         --  If the node denotes the range of a type mark, that is also the
-         --  resulting type, and we do not need to create an Itype for it.
+         when Float_Kind =>
+            return Nkind_In (Constraint_Kind, N_Digits_Constraint,
+                                              N_Range_Constraint);
 
-         if Is_Entity_Name (Prefix (N))
-           and then Comes_From_Source (N)
-           and then Is_Type (Entity (Prefix (N)))
-           and then Is_Discrete_Type (Entity (Prefix (N)))
-         then
-            Def_Id := Entity (Prefix (N));
-         end if;
+         when Access_Kind       |
+              Array_Kind        |
+              E_Record_Type     |
+              E_Record_Subtype  |
+              Class_Wide_Kind   |
+              E_Incomplete_Type |
+              Private_Kind      |
+              Concurrent_Kind  =>
+            return Constraint_Kind = N_Index_Or_Discriminant_Constraint;
 
-         Analyze_And_Resolve (N);
-         T := Etype (N);
-         R := N;
+         when others =>
+            return True; -- Error will be detected later
+      end case;
+   end Is_Valid_Constraint_Kind;
 
-      --  If none of the above, must be a subtype. We convert this to a
-      --  range attribute reference because in the case of declared first
-      --  named subtypes, the types in the range reference can be different
-      --  from the type of the entity. A range attribute normalizes the
-      --  reference and obtains the correct types for the bounds.
+   --------------------------
+   -- Is_Visible_Component --
+   --------------------------
 
-      --  This transformation is in the nature of an expansion, is only
-      --  done if expansion is active. In particular, it is not done on
-      --  formal generic types,  because we need to retain the name of the
-      --  original index for instantiation purposes.
+   function Is_Visible_Component
+     (C : Entity_Id;
+      N : Node_Id := Empty) return Boolean
+   is
+      Original_Comp  : Entity_Id := Empty;
+      Original_Scope : Entity_Id;
+      Type_Scope     : Entity_Id;
 
-      else
-         if not Is_Entity_Name (N) or else not Is_Type (Entity (N)) then
-            Error_Msg_N ("invalid subtype mark in discrete range ", N);
-            Set_Etype (N, Any_Integer);
-            return;
+      function Is_Local_Type (Typ : Entity_Id) return Boolean;
+      --  Check whether parent type of inherited component is declared locally,
+      --  possibly within a nested package or instance. The current scope is
+      --  the derived record itself.
 
-         else
-            --  The type mark may be that of an incomplete type. It is only
-            --  now that we can get the full view, previous analysis does
-            --  not look specifically for a type mark.
+      -------------------
+      -- Is_Local_Type --
+      -------------------
 
-            Set_Entity (N, Get_Full_View (Entity (N)));
-            Set_Etype  (N, Entity (N));
-            Def_Id := Entity (N);
+      function Is_Local_Type (Typ : Entity_Id) return Boolean is
+         Scop : Entity_Id;
 
-            if not Is_Discrete_Type (Def_Id) then
-               Error_Msg_N ("discrete type required for index", N);
-               Set_Etype (N, Any_Type);
-               return;
+      begin
+         Scop := Scope (Typ);
+         while Present (Scop)
+           and then Scop /= Standard_Standard
+         loop
+            if Scop = Scope (Current_Scope) then
+               return True;
             end if;
-         end if;
-
-         if Expander_Active then
-            Rewrite (N,
-              Make_Attribute_Reference (Sloc (N),
-                Attribute_Name => Name_Range,
-                Prefix         => Relocate_Node (N)));
 
-            --  The original was a subtype mark that does not freeze. This
-            --  means that the rewritten version must not freeze either.
+            Scop := Scope (Scop);
+         end loop;
 
-            Set_Must_Not_Freeze (N);
-            Set_Must_Not_Freeze (Prefix (N));
-            Analyze_And_Resolve (N);
-            T := Etype (N);
-            R := N;
+         return False;
+      end Is_Local_Type;
 
-         --  If expander is inactive, type is legal, nothing else to construct
+   --  Start of processing for Is_Visible_Component
 
-         else
-            return;
-         end if;
+   begin
+      if Ekind_In (C, E_Component, E_Discriminant) then
+         Original_Comp := Original_Record_Component (C);
       end if;
 
-      if not Is_Discrete_Type (T) then
-         Error_Msg_N ("discrete type required for range", N);
-         Set_Etype (N, Any_Type);
-         return;
+      if No (Original_Comp) then
 
-      elsif T = Any_Type then
-         Set_Etype (N, Any_Type);
-         return;
+         --  Premature usage, or previous error
+
+         return False;
+
+      else
+         Original_Scope := Scope (Original_Comp);
+         Type_Scope     := Scope (Base_Type (Scope (C)));
       end if;
 
-      --  We will now create the appropriate Itype to describe the range, but
-      --  first a check. If we originally had a subtype, then we just label
-      --  the range with this subtype. Not only is there no need to construct
-      --  a new subtype, but it is wrong to do so for two reasons:
+      --  This test only concerns tagged types
 
-      --    1. A legality concern, if we have a subtype, it must not freeze,
-      --       and the Itype would cause freezing incorrectly
+      if not Is_Tagged_Type (Original_Scope) then
+         return True;
 
-      --    2. An efficiency concern, if we created an Itype, it would not be
-      --       recognized as the same type for the purposes of eliminating
-      --       checks in some circumstances.
+      --  If it is _Parent or _Tag, there is no visibility issue
 
-      --  We signal this case by setting the subtype entity in Def_Id
+      elsif not Comes_From_Source (Original_Comp) then
+         return True;
 
-      if No (Def_Id) then
-         Def_Id :=
-           Create_Itype (E_Void, Related_Nod, Related_Id, 'D', Suffix_Index);
-         Set_Etype (Def_Id, Base_Type (T));
+      --  Discriminants are visible unless the (private) type has unknown
+      --  discriminants. If the discriminant reference is inserted for a
+      --  discriminant check on a full view it is also visible.
 
-         if Is_Signed_Integer_Type (T) then
-            Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
+      elsif Ekind (Original_Comp) = E_Discriminant
+        and then
+          (not Has_Unknown_Discriminants (Original_Scope)
+            or else (Present (N)
+                      and then Nkind (N) = N_Selected_Component
+                      and then Nkind (Prefix (N)) = N_Type_Conversion
+                      and then not Comes_From_Source (Prefix (N))))
+      then
+         return True;
 
-         elsif Is_Modular_Integer_Type (T) then
-            Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
+      --  In the body of an instantiation, no need to check for the visibility
+      --  of a component.
 
-         else
-            Set_Ekind             (Def_Id, E_Enumeration_Subtype);
-            Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
-            Set_First_Literal     (Def_Id, First_Literal (T));
-         end if;
+      elsif In_Instance_Body then
+         return True;
 
-         Set_Size_Info      (Def_Id,                  (T));
-         Set_RM_Size        (Def_Id, RM_Size          (T));
-         Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
+      --  If the component has been declared in an ancestor which is currently
+      --  a private type, then it is not visible. The same applies if the
+      --  component's containing type is not in an open scope and the original
+      --  component's enclosing type is a visible full view of a private type
+      --  (which can occur in cases where an attempt is being made to reference
+      --  a component in a sibling package that is inherited from a visible
+      --  component of a type in an ancestor package; the component in the
+      --  sibling package should not be visible even though the component it
+      --  inherited from is visible). This does not apply however in the case
+      --  where the scope of the type is a private child unit, or when the
+      --  parent comes from a local package in which the ancestor is currently
+      --  visible. The latter suppression of visibility is needed for cases
+      --  that are tested in B730006.
 
-         Set_Scalar_Range   (Def_Id, R);
-         Conditional_Delay  (Def_Id, T);
+      elsif Is_Private_Type (Original_Scope)
+        or else
+          (not Is_Private_Descendant (Type_Scope)
+            and then not In_Open_Scopes (Type_Scope)
+            and then Has_Private_Declaration (Original_Scope))
+      then
+         --  If the type derives from an entity in a formal package, there
+         --  are no additional visible components.
 
-         if Nkind (N) = N_Subtype_Indication then
-            Inherit_Predicate_Flags (Def_Id, Entity (Subtype_Mark (N)));
-         end if;
+         if Nkind (Original_Node (Unit_Declaration_Node (Type_Scope))) =
+            N_Formal_Package_Declaration
+         then
+            return False;
 
-         --  In the subtype indication case, if the immediate parent of the
-         --  new subtype is non-static, then the subtype we create is non-
-         --  static, even if its bounds are static.
+         --  if we are not in the private part of the current package, there
+         --  are no additional visible components.
 
-         if Nkind (N) = N_Subtype_Indication
-           and then not Is_OK_Static_Subtype (Entity (Subtype_Mark (N)))
+         elsif Ekind (Scope (Current_Scope)) = E_Package
+           and then not In_Private_Part (Scope (Current_Scope))
          then
-            Set_Is_Non_Static_Subtype (Def_Id);
+            return False;
+         else
+            return
+              Is_Child_Unit (Cunit_Entity (Current_Sem_Unit))
+                and then In_Open_Scopes (Scope (Original_Scope))
+                and then Is_Local_Type (Type_Scope);
          end if;
-      end if;
 
-      --  Final step is to label the index with this constructed type
+      --  There is another weird way in which a component may be invisible when
+      --  the private and the full view are not derived from the same ancestor.
+      --  Here is an example :
 
-      Set_Etype (N, Def_Id);
-   end Make_Index;
+      --       type A1 is tagged      record F1 : integer; end record;
+      --       type A2 is new A1 with record F2 : integer; end record;
+      --       type T is new A1 with private;
+      --     private
+      --       type T is new A2 with null record;
 
-   ------------------------------
-   -- Modular_Type_Declaration --
-   ------------------------------
+      --  In this case, the full view of T inherits F1 and F2 but the private
+      --  view inherits only F1
 
-   procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id) is
-      Mod_Expr : constant Node_Id := Expression (Def);
-      M_Val    : Uint;
+      else
+         declare
+            Ancestor : Entity_Id := Scope (C);
 
-      procedure Set_Modular_Size (Bits : Int);
-      --  Sets RM_Size to Bits, and Esize to normal word size above this
+         begin
+            loop
+               if Ancestor = Original_Scope then
+                  return True;
+               elsif Ancestor = Etype (Ancestor) then
+                  return False;
+               end if;
 
-      ----------------------
-      -- Set_Modular_Size --
-      ----------------------
+               Ancestor := Etype (Ancestor);
+            end loop;
+         end;
+      end if;
+   end Is_Visible_Component;
 
-      procedure Set_Modular_Size (Bits : Int) is
-      begin
-         Set_RM_Size (T, UI_From_Int (Bits));
+   --------------------------
+   -- Make_Class_Wide_Type --
+   --------------------------
+
+   procedure Make_Class_Wide_Type (T : Entity_Id) is
+      CW_Type : Entity_Id;
+      CW_Name : Name_Id;
+      Next_E  : Entity_Id;
+
+   begin
+      if Present (Class_Wide_Type (T)) then
 
-         if Bits <= 8 then
-            Init_Esize (T, 8);
+         --  The class-wide type is a partially decorated entity created for a
+         --  unanalyzed tagged type referenced through a limited with clause.
+         --  When the tagged type is analyzed, its class-wide type needs to be
+         --  redecorated. Note that we reuse the entity created by Decorate_
+         --  Tagged_Type in order to preserve all links.
 
-         elsif Bits <= 16 then
-            Init_Esize (T, 16);
+         if Materialize_Entity (Class_Wide_Type (T)) then
+            CW_Type := Class_Wide_Type (T);
+            Set_Materialize_Entity (CW_Type, False);
 
-         elsif Bits <= 32 then
-            Init_Esize (T, 32);
+         --  The class wide type can have been defined by the partial view, in
+         --  which case everything is already done.
 
          else
-            Init_Esize (T, System_Max_Binary_Modulus_Power);
-         end if;
-
-         if not Non_Binary_Modulus (T)
-           and then Esize (T) = RM_Size (T)
-         then
-            Set_Is_Known_Valid (T);
+            return;
          end if;
-      end Set_Modular_Size;
-
-   --  Start of processing for Modular_Type_Declaration
 
-   begin
-      --  If the mod expression is (exactly) 2 * literal, where literal is
-      --  64 or less,then almost certainly the * was meant to be **. Warn.
+      --  Default case, we need to create a new class-wide type
 
-      if Warn_On_Suspicious_Modulus_Value
-        and then Nkind (Mod_Expr) = N_Op_Multiply
-        and then Nkind (Left_Opnd (Mod_Expr)) = N_Integer_Literal
-        and then Intval (Left_Opnd (Mod_Expr)) = Uint_2
-        and then Nkind (Right_Opnd (Mod_Expr)) = N_Integer_Literal
-        and then Intval (Right_Opnd (Mod_Expr)) <= Uint_64
-      then
-         Error_Msg_N
-           ("suspicious MOD value, was '*'* intended'??M?", Mod_Expr);
+      else
+         CW_Type :=
+           New_External_Entity (E_Void, Scope (T), Sloc (T), T, 'C', 0, 'T');
       end if;
 
-      --  Proceed with analysis of mod expression
-
-      Analyze_And_Resolve (Mod_Expr, Any_Integer);
-      Set_Etype (T, T);
-      Set_Ekind (T, E_Modular_Integer_Type);
-      Init_Alignment (T);
-      Set_Is_Constrained (T);
+      --  Inherit root type characteristics
 
-      if not Is_OK_Static_Expression (Mod_Expr) then
-         Flag_Non_Static_Expr
-           ("non-static expression used for modular type bound!", Mod_Expr);
-         M_Val := 2 ** System_Max_Binary_Modulus_Power;
-      else
-         M_Val := Expr_Value (Mod_Expr);
-      end if;
+      CW_Name := Chars (CW_Type);
+      Next_E  := Next_Entity (CW_Type);
+      Copy_Node (T, CW_Type);
+      Set_Comes_From_Source (CW_Type, False);
+      Set_Chars (CW_Type, CW_Name);
+      Set_Parent (CW_Type, Parent (T));
+      Set_Next_Entity (CW_Type, Next_E);
 
-      if M_Val < 1 then
-         Error_Msg_N ("modulus value must be positive", Mod_Expr);
-         M_Val := 2 ** System_Max_Binary_Modulus_Power;
-      end if;
+      --  Ensure we have a new freeze node for the class-wide type. The partial
+      --  view may have freeze action of its own, requiring a proper freeze
+      --  node, and the same freeze node cannot be shared between the two
+      --  types.
 
-      if M_Val > 2 ** Standard_Long_Integer_Size then
-         Check_Restriction (No_Long_Long_Integers, Mod_Expr);
-      end if;
+      Set_Has_Delayed_Freeze (CW_Type);
+      Set_Freeze_Node (CW_Type, Empty);
 
-      Set_Modulus (T, M_Val);
+      --  Customize the class-wide type: It has no prim. op., it cannot be
+      --  abstract and its Etype points back to the specific root type.
 
-      --   Create bounds for the modular type based on the modulus given in
-      --   the type declaration and then analyze and resolve those bounds.
+      Set_Ekind                       (CW_Type, E_Class_Wide_Type);
+      Set_Is_Tagged_Type              (CW_Type, True);
+      Set_Direct_Primitive_Operations (CW_Type, New_Elmt_List);
+      Set_Is_Abstract_Type            (CW_Type, False);
+      Set_Is_Constrained              (CW_Type, False);
+      Set_Is_First_Subtype            (CW_Type, Is_First_Subtype (T));
+      Set_Default_SSO                 (CW_Type);
 
-      Set_Scalar_Range (T,
-        Make_Range (Sloc (Mod_Expr),
-          Low_Bound  => Make_Integer_Literal (Sloc (Mod_Expr), 0),
-          High_Bound => Make_Integer_Literal (Sloc (Mod_Expr), M_Val - 1)));
+      if Ekind (T) = E_Class_Wide_Subtype then
+         Set_Etype (CW_Type, Etype (Base_Type (T)));
+      else
+         Set_Etype (CW_Type, T);
+      end if;
 
-      --  Properly analyze the literals for the range. We do this manually
-      --  because we can't go calling Resolve, since we are resolving these
-      --  bounds with the type, and this type is certainly not complete yet.
+      Set_No_Tagged_Streams_Pragma (CW_Type, No_Tagged_Streams);
 
-      Set_Etype (Low_Bound  (Scalar_Range (T)), T);
-      Set_Etype (High_Bound (Scalar_Range (T)), T);
-      Set_Is_Static_Expression (Low_Bound  (Scalar_Range (T)));
-      Set_Is_Static_Expression (High_Bound (Scalar_Range (T)));
+      --  If this is the class_wide type of a constrained subtype, it does
+      --  not have discriminants.
 
-      --  Loop through powers of two to find number of bits required
+      Set_Has_Discriminants (CW_Type,
+        Has_Discriminants (T) and then not Is_Constrained (T));
 
-      for Bits in Int range 0 .. System_Max_Binary_Modulus_Power loop
+      Set_Has_Unknown_Discriminants (CW_Type, True);
+      Set_Class_Wide_Type (T, CW_Type);
+      Set_Equivalent_Type (CW_Type, Empty);
 
-         --  Binary case
+      --  The class-wide type of a class-wide type is itself (RM 3.9(14))
 
-         if M_Val = 2 ** Bits then
-            Set_Modular_Size (Bits);
-            return;
+      Set_Class_Wide_Type (CW_Type, CW_Type);
+   end Make_Class_Wide_Type;
 
-         --  Non-binary case
+   ----------------
+   -- Make_Index --
+   ----------------
 
-         elsif M_Val < 2 ** Bits then
-            Check_SPARK_Restriction ("modulus should be a power of 2", T);
-            Set_Non_Binary_Modulus (T);
+   procedure Make_Index
+     (N            : Node_Id;
+      Related_Nod  : Node_Id;
+      Related_Id   : Entity_Id := Empty;
+      Suffix_Index : Nat       := 1;
+      In_Iter_Schm : Boolean   := False)
+   is
+      R      : Node_Id;
+      T      : Entity_Id;
+      Def_Id : Entity_Id := Empty;
+      Found  : Boolean := False;
 
-            if Bits > System_Max_Nonbinary_Modulus_Power then
-               Error_Msg_Uint_1 :=
-                 UI_From_Int (System_Max_Nonbinary_Modulus_Power);
-               Error_Msg_F
-                 ("nonbinary modulus exceeds limit (2 '*'*^ - 1)", Mod_Expr);
-               Set_Modular_Size (System_Max_Binary_Modulus_Power);
-               return;
+   begin
+      --  For a discrete range used in a constrained array definition and
+      --  defined by a range, an implicit conversion to the predefined type
+      --  INTEGER is assumed if each bound is either a numeric literal, a named
+      --  number, or an attribute, and the type of both bounds (prior to the
+      --  implicit conversion) is the type universal_integer. Otherwise, both
+      --  bounds must be of the same discrete type, other than universal
+      --  integer; this type must be determinable independently of the
+      --  context, but using the fact that the type must be discrete and that
+      --  both bounds must have the same type.
 
-            else
-               --  In the non-binary case, set size as per RM 13.3(55)
+      --  Character literals also have a universal type in the absence of
+      --  of additional context,  and are resolved to Standard_Character.
 
-               Set_Modular_Size (Bits);
-               return;
-            end if;
-         end if;
+      if Nkind (N) = N_Range then
 
-      end loop;
+         --  The index is given by a range constraint. The bounds are known
+         --  to be of a consistent type.
 
-      --  If we fall through, then the size exceed System.Max_Binary_Modulus
-      --  so we just signal an error and set the maximum size.
+         if not Is_Overloaded (N) then
+            T := Etype (N);
 
-      Error_Msg_Uint_1 := UI_From_Int (System_Max_Binary_Modulus_Power);
-      Error_Msg_F ("modulus exceeds limit (2 '*'*^)", Mod_Expr);
+            --  For universal bounds, choose the specific predefined type
 
-      Set_Modular_Size (System_Max_Binary_Modulus_Power);
-      Init_Alignment (T);
+            if T = Universal_Integer then
+               T := Standard_Integer;
 
-   end Modular_Type_Declaration;
+            elsif T = Any_Character then
+               Ambiguous_Character (Low_Bound (N));
 
-   --------------------------
-   -- New_Concatenation_Op --
-   --------------------------
+               T := Standard_Character;
+            end if;
 
-   procedure New_Concatenation_Op (Typ : Entity_Id) is
-      Loc : constant Source_Ptr := Sloc (Typ);
-      Op  : Entity_Id;
+         --  The node may be overloaded because some user-defined operators
+         --  are available, but if a universal interpretation exists it is
+         --  also the selected one.
 
-      function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id;
-      --  Create abbreviated declaration for the formal of a predefined
-      --  Operator 'Op' of type 'Typ'
+         elsif Universal_Interpretation (N) = Universal_Integer then
+            T := Standard_Integer;
 
-      --------------------
-      -- Make_Op_Formal --
-      --------------------
+         else
+            T := Any_Type;
 
-      function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id is
-         Formal : Entity_Id;
-      begin
-         Formal := New_Internal_Entity (E_In_Parameter, Op, Loc, 'P');
-         Set_Etype (Formal, Typ);
-         Set_Mechanism (Formal, Default_Mechanism);
-         return Formal;
-      end Make_Op_Formal;
+            declare
+               Ind : Interp_Index;
+               It  : Interp;
 
-   --  Start of processing for New_Concatenation_Op
+            begin
+               Get_First_Interp (N, Ind, It);
+               while Present (It.Typ) loop
+                  if Is_Discrete_Type (It.Typ) then
 
-   begin
-      Op := Make_Defining_Operator_Symbol (Loc, Name_Op_Concat);
+                     if Found
+                       and then not Covers (It.Typ, T)
+                       and then not Covers (T, It.Typ)
+                     then
+                        Error_Msg_N ("ambiguous bounds in discrete range", N);
+                        exit;
+                     else
+                        T := It.Typ;
+                        Found := True;
+                     end if;
+                  end if;
 
-      Set_Ekind                   (Op, E_Operator);
-      Set_Scope                   (Op, Current_Scope);
-      Set_Etype                   (Op, Typ);
-      Set_Homonym                 (Op, Get_Name_Entity_Id (Name_Op_Concat));
-      Set_Is_Immediately_Visible  (Op);
-      Set_Is_Intrinsic_Subprogram (Op);
-      Set_Has_Completion          (Op);
-      Append_Entity               (Op, Current_Scope);
+                  Get_Next_Interp (Ind, It);
+               end loop;
 
-      Set_Name_Entity_Id (Name_Op_Concat, Op);
+               if T = Any_Type then
+                  Error_Msg_N ("discrete type required for range", N);
+                  Set_Etype (N, Any_Type);
+                  return;
 
-      Append_Entity (Make_Op_Formal (Typ, Op), Op);
-      Append_Entity (Make_Op_Formal (Typ, Op), Op);
-   end New_Concatenation_Op;
+               elsif T = Universal_Integer then
+                  T := Standard_Integer;
+               end if;
+            end;
+         end if;
 
-   -------------------------
-   -- OK_For_Limited_Init --
-   -------------------------
+         if not Is_Discrete_Type (T) then
+            Error_Msg_N ("discrete type required for range", N);
+            Set_Etype (N, Any_Type);
+            return;
+         end if;
 
-   --  ???Check all calls of this, and compare the conditions under which it's
-   --  called.
+         if Nkind (Low_Bound (N)) = N_Attribute_Reference
+           and then Attribute_Name (Low_Bound (N)) = Name_First
+           and then Is_Entity_Name (Prefix (Low_Bound (N)))
+           and then Is_Type (Entity (Prefix (Low_Bound (N))))
+           and then Is_Discrete_Type (Entity (Prefix (Low_Bound (N))))
+         then
+            --  The type of the index will be the type of the prefix, as long
+            --  as the upper bound is 'Last of the same type.
 
-   function OK_For_Limited_Init
-     (Typ : Entity_Id;
-      Exp : Node_Id) return Boolean
-   is
-   begin
-      return Is_CPP_Constructor_Call (Exp)
-        or else (Ada_Version >= Ada_2005
-                  and then not Debug_Flag_Dot_L
-                  and then OK_For_Limited_Init_In_05 (Typ, Exp));
-   end OK_For_Limited_Init;
+            Def_Id := Entity (Prefix (Low_Bound (N)));
 
-   -------------------------------
-   -- OK_For_Limited_Init_In_05 --
-   -------------------------------
+            if Nkind (High_Bound (N)) /= N_Attribute_Reference
+              or else Attribute_Name (High_Bound (N)) /= Name_Last
+              or else not Is_Entity_Name (Prefix (High_Bound (N)))
+              or else Entity (Prefix (High_Bound (N))) /= Def_Id
+            then
+               Def_Id := Empty;
+            end if;
+         end if;
 
-   function OK_For_Limited_Init_In_05
-     (Typ : Entity_Id;
-      Exp : Node_Id) return Boolean
-   is
-   begin
-      --  An object of a limited interface type can be initialized with any
-      --  expression of a nonlimited descendant type.
+         R := N;
+         Process_Range_Expr_In_Decl (R, T, In_Iter_Schm => In_Iter_Schm);
 
-      if Is_Class_Wide_Type (Typ)
-        and then Is_Limited_Interface (Typ)
-        and then not Is_Limited_Type (Etype (Exp))
-      then
-         return True;
-      end if;
+      elsif Nkind (N) = N_Subtype_Indication then
 
-      --  Ada 2005 (AI-287, AI-318): Relax the strictness of the front end in
-      --  case of limited aggregates (including extension aggregates), and
-      --  function calls. The function call may have been given in prefixed
-      --  notation, in which case the original node is an indexed component.
-      --  If the function is parameterless, the original node was an explicit
-      --  dereference. The function may also be parameterless, in which case
-      --  the source node is just an identifier.
+         --  The index is given by a subtype with a range constraint
 
-      case Nkind (Original_Node (Exp)) is
-         when N_Aggregate | N_Extension_Aggregate | N_Function_Call | N_Op =>
-            return True;
+         T :=  Base_Type (Entity (Subtype_Mark (N)));
 
-         when N_Identifier =>
-            return Present (Entity (Original_Node (Exp)))
-              and then Ekind (Entity (Original_Node (Exp))) = E_Function;
+         if not Is_Discrete_Type (T) then
+            Error_Msg_N ("discrete type required for range", N);
+            Set_Etype (N, Any_Type);
+            return;
+         end if;
 
-         when N_Qualified_Expression =>
-            return
-              OK_For_Limited_Init_In_05
-                (Typ, Expression (Original_Node (Exp)));
+         R := Range_Expression (Constraint (N));
 
-         --  Ada 2005 (AI-251): If a class-wide interface object is initialized
-         --  with a function call, the expander has rewritten the call into an
-         --  N_Type_Conversion node to force displacement of the pointer to
-         --  reference the component containing the secondary dispatch table.
-         --  Otherwise a type conversion is not a legal context.
-         --  A return statement for a build-in-place function returning a
-         --  synchronized type also introduces an unchecked conversion.
+         Resolve (R, T);
+         Process_Range_Expr_In_Decl
+           (R, Entity (Subtype_Mark (N)), In_Iter_Schm => In_Iter_Schm);
 
-         when N_Type_Conversion           |
-              N_Unchecked_Type_Conversion =>
-            return not Comes_From_Source (Exp)
-              and then
-                OK_For_Limited_Init_In_05
-                  (Typ, Expression (Original_Node (Exp)));
+      elsif Nkind (N) = N_Attribute_Reference then
 
-         when N_Indexed_Component     |
-              N_Selected_Component    |
-              N_Explicit_Dereference  =>
-            return Nkind (Exp) = N_Function_Call;
+         --  Catch beginner's error (use of attribute other than 'Range)
 
-         --  A use of 'Input is a function call, hence allowed. Normally the
-         --  attribute will be changed to a call, but the attribute by itself
-         --  can occur with -gnatc.
+         if Attribute_Name (N) /= Name_Range then
+            Error_Msg_N ("expect attribute ''Range", N);
+            Set_Etype (N, Any_Type);
+            return;
+         end if;
 
-         when N_Attribute_Reference =>
-            return Attribute_Name (Original_Node (Exp)) = Name_Input;
+         --  If the node denotes the range of a type mark, that is also the
+         --  resulting type, and we do not need to create an Itype for it.
 
-         --  For a case expression, all dependent expressions must be legal
+         if Is_Entity_Name (Prefix (N))
+           and then Comes_From_Source (N)
+           and then Is_Type (Entity (Prefix (N)))
+           and then Is_Discrete_Type (Entity (Prefix (N)))
+         then
+            Def_Id := Entity (Prefix (N));
+         end if;
 
-         when N_Case_Expression =>
-            declare
-               Alt : Node_Id;
+         Analyze_And_Resolve (N);
+         T := Etype (N);
+         R := N;
 
-            begin
-               Alt := First (Alternatives (Original_Node (Exp)));
-               while Present (Alt) loop
-                  if not OK_For_Limited_Init_In_05 (Typ, Expression (Alt)) then
-                     return False;
-                  end if;
+      --  If none of the above, must be a subtype. We convert this to a
+      --  range attribute reference because in the case of declared first
+      --  named subtypes, the types in the range reference can be different
+      --  from the type of the entity. A range attribute normalizes the
+      --  reference and obtains the correct types for the bounds.
 
-                  Next (Alt);
-               end loop;
+      --  This transformation is in the nature of an expansion, is only
+      --  done if expansion is active. In particular, it is not done on
+      --  formal generic types,  because we need to retain the name of the
+      --  original index for instantiation purposes.
 
-               return True;
-            end;
+      else
+         if not Is_Entity_Name (N) or else not Is_Type (Entity (N)) then
+            Error_Msg_N ("invalid subtype mark in discrete range ", N);
+            Set_Etype (N, Any_Integer);
+            return;
 
-         --  For an if expression, all dependent expressions must be legal
+         else
+            --  The type mark may be that of an incomplete type. It is only
+            --  now that we can get the full view, previous analysis does
+            --  not look specifically for a type mark.
 
-         when N_If_Expression =>
-            declare
-               Then_Expr : constant Node_Id :=
-                             Next (First (Expressions (Original_Node (Exp))));
-               Else_Expr : constant Node_Id := Next (Then_Expr);
-            begin
-               return OK_For_Limited_Init_In_05 (Typ, Then_Expr)
-                        and then
-                      OK_For_Limited_Init_In_05 (Typ, Else_Expr);
-            end;
+            Set_Entity (N, Get_Full_View (Entity (N)));
+            Set_Etype  (N, Entity (N));
+            Def_Id := Entity (N);
 
-         when others =>
-            return False;
-      end case;
-   end OK_For_Limited_Init_In_05;
+            if not Is_Discrete_Type (Def_Id) then
+               Error_Msg_N ("discrete type required for index", N);
+               Set_Etype (N, Any_Type);
+               return;
+            end if;
+         end if;
 
-   -------------------------------------------
-   -- Ordinary_Fixed_Point_Type_Declaration --
-   -------------------------------------------
+         if Expander_Active then
+            Rewrite (N,
+              Make_Attribute_Reference (Sloc (N),
+                Attribute_Name => Name_Range,
+                Prefix         => Relocate_Node (N)));
 
-   procedure Ordinary_Fixed_Point_Type_Declaration
-     (T   : Entity_Id;
-      Def : Node_Id)
-   is
-      Loc           : constant Source_Ptr := Sloc (Def);
-      Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
-      RRS           : constant Node_Id    := Real_Range_Specification (Def);
-      Implicit_Base : Entity_Id;
-      Delta_Val     : Ureal;
-      Small_Val     : Ureal;
-      Low_Val       : Ureal;
-      High_Val      : Ureal;
+            --  The original was a subtype mark that does not freeze. This
+            --  means that the rewritten version must not freeze either.
 
-   begin
-      Check_Restriction (No_Fixed_Point, Def);
+            Set_Must_Not_Freeze (N);
+            Set_Must_Not_Freeze (Prefix (N));
+            Analyze_And_Resolve (N);
+            T := Etype (N);
+            R := N;
 
-      --  Create implicit base type
+         --  If expander is inactive, type is legal, nothing else to construct
 
-      Implicit_Base :=
-        Create_Itype (E_Ordinary_Fixed_Point_Type, Parent (Def), T, 'B');
-      Set_Etype (Implicit_Base, Implicit_Base);
+         else
+            return;
+         end if;
+      end if;
 
-      --  Analyze and process delta expression
+      if not Is_Discrete_Type (T) then
+         Error_Msg_N ("discrete type required for range", N);
+         Set_Etype (N, Any_Type);
+         return;
 
-      Analyze_And_Resolve (Delta_Expr, Any_Real);
+      elsif T = Any_Type then
+         Set_Etype (N, Any_Type);
+         return;
+      end if;
 
-      Check_Delta_Expression (Delta_Expr);
-      Delta_Val := Expr_Value_R (Delta_Expr);
+      --  We will now create the appropriate Itype to describe the range, but
+      --  first a check. If we originally had a subtype, then we just label
+      --  the range with this subtype. Not only is there no need to construct
+      --  a new subtype, but it is wrong to do so for two reasons:
 
-      Set_Delta_Value (Implicit_Base, Delta_Val);
+      --    1. A legality concern, if we have a subtype, it must not freeze,
+      --       and the Itype would cause freezing incorrectly
 
-      --  Compute default small from given delta, which is the largest power
-      --  of two that does not exceed the given delta value.
+      --    2. An efficiency concern, if we created an Itype, it would not be
+      --       recognized as the same type for the purposes of eliminating
+      --       checks in some circumstances.
 
-      declare
-         Tmp   : Ureal;
-         Scale : Int;
+      --  We signal this case by setting the subtype entity in Def_Id
 
-      begin
-         Tmp := Ureal_1;
-         Scale := 0;
+      if No (Def_Id) then
+         Def_Id :=
+           Create_Itype (E_Void, Related_Nod, Related_Id, 'D', Suffix_Index);
+         Set_Etype (Def_Id, Base_Type (T));
 
-         if Delta_Val < Ureal_1 then
-            while Delta_Val < Tmp loop
-               Tmp := Tmp / Ureal_2;
-               Scale := Scale + 1;
-            end loop;
+         if Is_Signed_Integer_Type (T) then
+            Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
+
+         elsif Is_Modular_Integer_Type (T) then
+            Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
 
          else
-            loop
-               Tmp := Tmp * Ureal_2;
-               exit when Tmp > Delta_Val;
-               Scale := Scale - 1;
-            end loop;
+            Set_Ekind             (Def_Id, E_Enumeration_Subtype);
+            Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
+            Set_First_Literal     (Def_Id, First_Literal (T));
          end if;
 
-         Small_Val := UR_From_Components (Uint_1, UI_From_Int (Scale), 2);
-      end;
+         Set_Size_Info      (Def_Id,                  (T));
+         Set_RM_Size        (Def_Id, RM_Size          (T));
+         Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
 
-      Set_Small_Value (Implicit_Base, Small_Val);
+         Set_Scalar_Range   (Def_Id, R);
+         Conditional_Delay  (Def_Id, T);
 
-      --  If no range was given, set a dummy range
+         if Nkind (N) = N_Subtype_Indication then
+            Inherit_Predicate_Flags (Def_Id, Entity (Subtype_Mark (N)));
+         end if;
 
-      if RRS <= Empty_Or_Error then
-         Low_Val  := -Small_Val;
-         High_Val := Small_Val;
+         --  In the subtype indication case, if the immediate parent of the
+         --  new subtype is non-static, then the subtype we create is non-
+         --  static, even if its bounds are static.
 
-      --  Otherwise analyze and process given range
+         if Nkind (N) = N_Subtype_Indication
+           and then not Is_OK_Static_Subtype (Entity (Subtype_Mark (N)))
+         then
+            Set_Is_Non_Static_Subtype (Def_Id);
+         end if;
+      end if;
 
-      else
-         declare
-            Low  : constant Node_Id := Low_Bound  (RRS);
-            High : constant Node_Id := High_Bound (RRS);
+      --  Final step is to label the index with this constructed type
 
-         begin
-            Analyze_And_Resolve (Low, Any_Real);
-            Analyze_And_Resolve (High, Any_Real);
-            Check_Real_Bound (Low);
-            Check_Real_Bound (High);
+      Set_Etype (N, Def_Id);
+   end Make_Index;
 
-            --  Obtain and set the range
+   ------------------------------
+   -- Modular_Type_Declaration --
+   ------------------------------
 
-            Low_Val  := Expr_Value_R (Low);
-            High_Val := Expr_Value_R (High);
+   procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id) is
+      Mod_Expr : constant Node_Id := Expression (Def);
+      M_Val    : Uint;
 
-            if Low_Val > High_Val then
-               Error_Msg_NE ("??fixed point type& has null range", Def, T);
-            end if;
-         end;
-      end if;
+      procedure Set_Modular_Size (Bits : Int);
+      --  Sets RM_Size to Bits, and Esize to normal word size above this
 
-      --  The range for both the implicit base and the declared first subtype
-      --  cannot be set yet, so we use the special routine Set_Fixed_Range to
-      --  set a temporary range in place. Note that the bounds of the base
-      --  type will be widened to be symmetrical and to fill the available
-      --  bits when the type is frozen.
+      ----------------------
+      -- Set_Modular_Size --
+      ----------------------
 
-      --  We could do this with all discrete types, and probably should, but
-      --  we absolutely have to do it for fixed-point, since the end-points
-      --  of the range and the size are determined by the small value, which
-      --  could be reset before the freeze point.
+      procedure Set_Modular_Size (Bits : Int) is
+      begin
+         Set_RM_Size (T, UI_From_Int (Bits));
 
-      Set_Fixed_Range (Implicit_Base, Loc, Low_Val, High_Val);
-      Set_Fixed_Range (T, Loc, Low_Val, High_Val);
+         if Bits <= 8 then
+            Init_Esize (T, 8);
 
-      --  Complete definition of first subtype
+         elsif Bits <= 16 then
+            Init_Esize (T, 16);
 
-      Set_Ekind          (T, E_Ordinary_Fixed_Point_Subtype);
-      Set_Etype          (T, Implicit_Base);
-      Init_Size_Align    (T);
-      Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
-      Set_Small_Value    (T, Small_Val);
-      Set_Delta_Value    (T, Delta_Val);
-      Set_Is_Constrained (T);
+         elsif Bits <= 32 then
+            Init_Esize (T, 32);
 
-   end Ordinary_Fixed_Point_Type_Declaration;
+         else
+            Init_Esize (T, System_Max_Binary_Modulus_Power);
+         end if;
 
-   ----------------------------------------
-   -- Prepare_Private_Subtype_Completion --
-   ----------------------------------------
+         if not Non_Binary_Modulus (T) and then Esize (T) = RM_Size (T) then
+            Set_Is_Known_Valid (T);
+         end if;
+      end Set_Modular_Size;
 
-   procedure Prepare_Private_Subtype_Completion
-     (Id          : Entity_Id;
-      Related_Nod : Node_Id)
-   is
-      Id_B   : constant Entity_Id := Base_Type (Id);
-      Full_B : Entity_Id := Full_View (Id_B);
-      Full   : Entity_Id;
+   --  Start of processing for Modular_Type_Declaration
 
    begin
-      if Present (Full_B) then
+      --  If the mod expression is (exactly) 2 * literal, where literal is
+      --  64 or less,then almost certainly the * was meant to be **. Warn.
 
-         --  Get to the underlying full view if necessary
+      if Warn_On_Suspicious_Modulus_Value
+        and then Nkind (Mod_Expr) = N_Op_Multiply
+        and then Nkind (Left_Opnd (Mod_Expr)) = N_Integer_Literal
+        and then Intval (Left_Opnd (Mod_Expr)) = Uint_2
+        and then Nkind (Right_Opnd (Mod_Expr)) = N_Integer_Literal
+        and then Intval (Right_Opnd (Mod_Expr)) <= Uint_64
+      then
+         Error_Msg_N
+           ("suspicious MOD value, was '*'* intended'??M?", Mod_Expr);
+      end if;
 
-         if Is_Private_Type (Full_B)
-           and then Present (Underlying_Full_View (Full_B))
-         then
-            Full_B := Underlying_Full_View (Full_B);
-         end if;
+      --  Proceed with analysis of mod expression
 
-         --  The Base_Type is already completed, we can complete the subtype
-         --  now. We have to create a new entity with the same name, Thus we
-         --  can't use Create_Itype.
+      Analyze_And_Resolve (Mod_Expr, Any_Integer);
+      Set_Etype (T, T);
+      Set_Ekind (T, E_Modular_Integer_Type);
+      Init_Alignment (T);
+      Set_Is_Constrained (T);
 
-         Full := Make_Defining_Identifier (Sloc (Id), Chars (Id));
-         Set_Is_Itype (Full);
-         Set_Associated_Node_For_Itype (Full, Related_Nod);
-         Complete_Private_Subtype (Id, Full, Full_B, Related_Nod);
+      if not Is_OK_Static_Expression (Mod_Expr) then
+         Flag_Non_Static_Expr
+           ("non-static expression used for modular type bound!", Mod_Expr);
+         M_Val := 2 ** System_Max_Binary_Modulus_Power;
+      else
+         M_Val := Expr_Value (Mod_Expr);
       end if;
 
-      --  The parent subtype may be private, but the base might not, in some
-      --  nested instances. In that case, the subtype does not need to be
-      --  exchanged. It would still be nice to make private subtypes and their
-      --  bases consistent at all times ???
+      if M_Val < 1 then
+         Error_Msg_N ("modulus value must be positive", Mod_Expr);
+         M_Val := 2 ** System_Max_Binary_Modulus_Power;
+      end if;
 
-      if Is_Private_Type (Id_B) then
-         Append_Elmt (Id, Private_Dependents (Id_B));
+      if M_Val > 2 ** Standard_Long_Integer_Size then
+         Check_Restriction (No_Long_Long_Integers, Mod_Expr);
       end if;
-   end Prepare_Private_Subtype_Completion;
 
-   ---------------------------
-   -- Process_Discriminants --
-   ---------------------------
+      Set_Modulus (T, M_Val);
 
-   procedure Process_Discriminants
-     (N    : Node_Id;
-      Prev : Entity_Id := Empty)
-   is
-      Elist               : constant Elist_Id := New_Elmt_List;
-      Id                  : Node_Id;
-      Discr               : Node_Id;
-      Discr_Number        : Uint;
-      Discr_Type          : Entity_Id;
-      Default_Present     : Boolean := False;
-      Default_Not_Present : Boolean := False;
+      --   Create bounds for the modular type based on the modulus given in
+      --   the type declaration and then analyze and resolve those bounds.
 
-   begin
-      --  A composite type other than an array type can have discriminants.
-      --  On entry, the current scope is the composite type.
+      Set_Scalar_Range (T,
+        Make_Range (Sloc (Mod_Expr),
+          Low_Bound  => Make_Integer_Literal (Sloc (Mod_Expr), 0),
+          High_Bound => Make_Integer_Literal (Sloc (Mod_Expr), M_Val - 1)));
 
-      --  The discriminants are initially entered into the scope of the type
-      --  via Enter_Name with the default Ekind of E_Void to prevent premature
-      --  use, as explained at the end of this procedure.
+      --  Properly analyze the literals for the range. We do this manually
+      --  because we can't go calling Resolve, since we are resolving these
+      --  bounds with the type, and this type is certainly not complete yet.
 
-      Discr := First (Discriminant_Specifications (N));
-      while Present (Discr) loop
-         Enter_Name (Defining_Identifier (Discr));
+      Set_Etype (Low_Bound  (Scalar_Range (T)), T);
+      Set_Etype (High_Bound (Scalar_Range (T)), T);
+      Set_Is_Static_Expression (Low_Bound  (Scalar_Range (T)));
+      Set_Is_Static_Expression (High_Bound (Scalar_Range (T)));
 
-         --  For navigation purposes we add a reference to the discriminant
-         --  in the entity for the type. If the current declaration is a
-         --  completion, place references on the partial view. Otherwise the
-         --  type is the current scope.
+      --  Loop through powers of two to find number of bits required
 
-         if Present (Prev) then
+      for Bits in Int range 0 .. System_Max_Binary_Modulus_Power loop
 
-            --  The references go on the partial view, if present. If the
-            --  partial view has discriminants, the references have been
-            --  generated already.
+         --  Binary case
 
-            if not Has_Discriminants (Prev) then
-               Generate_Reference (Prev, Defining_Identifier (Discr), 'd');
-            end if;
-         else
-            Generate_Reference
-              (Current_Scope, Defining_Identifier (Discr), 'd');
-         end if;
+         if M_Val = 2 ** Bits then
+            Set_Modular_Size (Bits);
+            return;
 
-         if Nkind (Discriminant_Type (Discr)) = N_Access_Definition then
-            Discr_Type := Access_Definition (Discr, Discriminant_Type (Discr));
+         --  Non-binary case
 
-            --  Ada 2005 (AI-254)
+         elsif M_Val < 2 ** Bits then
+            Check_SPARK_05_Restriction ("modulus should be a power of 2", T);
+            Set_Non_Binary_Modulus (T);
 
-            if Present (Access_To_Subprogram_Definition
-                         (Discriminant_Type (Discr)))
-              and then Protected_Present (Access_To_Subprogram_Definition
-                                           (Discriminant_Type (Discr)))
-            then
-               Discr_Type :=
-                 Replace_Anonymous_Access_To_Protected_Subprogram (Discr);
-            end if;
+            if Bits > System_Max_Nonbinary_Modulus_Power then
+               Error_Msg_Uint_1 :=
+                 UI_From_Int (System_Max_Nonbinary_Modulus_Power);
+               Error_Msg_F
+                 ("nonbinary modulus exceeds limit (2 '*'*^ - 1)", Mod_Expr);
+               Set_Modular_Size (System_Max_Binary_Modulus_Power);
+               return;
 
-         else
-            Find_Type (Discriminant_Type (Discr));
-            Discr_Type := Etype (Discriminant_Type (Discr));
+            else
+               --  In the non-binary case, set size as per RM 13.3(55)
 
-            if Error_Posted (Discriminant_Type (Discr)) then
-               Discr_Type := Any_Type;
+               Set_Modular_Size (Bits);
+               return;
             end if;
          end if;
 
-         if Is_Access_Type (Discr_Type) then
+      end loop;
+
+      --  If we fall through, then the size exceed System.Max_Binary_Modulus
+      --  so we just signal an error and set the maximum size.
+
+      Error_Msg_Uint_1 := UI_From_Int (System_Max_Binary_Modulus_Power);
+      Error_Msg_F ("modulus exceeds limit (2 '*'*^)", Mod_Expr);
+
+      Set_Modular_Size (System_Max_Binary_Modulus_Power);
+      Init_Alignment (T);
+
+   end Modular_Type_Declaration;
 
-            --  Ada 2005 (AI-230): Access discriminant allowed in non-limited
-            --  record types
+   --------------------------
+   -- New_Concatenation_Op --
+   --------------------------
 
-            if Ada_Version < Ada_2005 then
-               Check_Access_Discriminant_Requires_Limited
-                 (Discr, Discriminant_Type (Discr));
-            end if;
+   procedure New_Concatenation_Op (Typ : Entity_Id) is
+      Loc : constant Source_Ptr := Sloc (Typ);
+      Op  : Entity_Id;
 
-            if Ada_Version = Ada_83 and then Comes_From_Source (Discr) then
-               Error_Msg_N
-                 ("(Ada 83) access discriminant not allowed", Discr);
-            end if;
+      function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id;
+      --  Create abbreviated declaration for the formal of a predefined
+      --  Operator 'Op' of type 'Typ'
 
-         elsif not Is_Discrete_Type (Discr_Type) then
-            Error_Msg_N ("discriminants must have a discrete or access type",
-              Discriminant_Type (Discr));
-         end if;
+      --------------------
+      -- Make_Op_Formal --
+      --------------------
 
-         Set_Etype (Defining_Identifier (Discr), Discr_Type);
+      function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id is
+         Formal : Entity_Id;
+      begin
+         Formal := New_Internal_Entity (E_In_Parameter, Op, Loc, 'P');
+         Set_Etype (Formal, Typ);
+         Set_Mechanism (Formal, Default_Mechanism);
+         return Formal;
+      end Make_Op_Formal;
 
-         --  If a discriminant specification includes the assignment compound
-         --  delimiter followed by an expression, the expression is the default
-         --  expression of the discriminant; the default expression must be of
-         --  the type of the discriminant. (RM 3.7.1) Since this expression is
-         --  a default expression, we do the special preanalysis, since this
-         --  expression does not freeze (see "Handling of Default and Per-
-         --  Object Expressions" in spec of package Sem).
+   --  Start of processing for New_Concatenation_Op
 
-         if Present (Expression (Discr)) then
-            Preanalyze_Spec_Expression (Expression (Discr), Discr_Type);
+   begin
+      Op := Make_Defining_Operator_Symbol (Loc, Name_Op_Concat);
 
-            --  Legaity checks
+      Set_Ekind                   (Op, E_Operator);
+      Set_Scope                   (Op, Current_Scope);
+      Set_Etype                   (Op, Typ);
+      Set_Homonym                 (Op, Get_Name_Entity_Id (Name_Op_Concat));
+      Set_Is_Immediately_Visible  (Op);
+      Set_Is_Intrinsic_Subprogram (Op);
+      Set_Has_Completion          (Op);
+      Append_Entity               (Op, Current_Scope);
 
-            if Nkind (N) = N_Formal_Type_Declaration then
-               Error_Msg_N
-                 ("discriminant defaults not allowed for formal type",
-                  Expression (Discr));
+      Set_Name_Entity_Id (Name_Op_Concat, Op);
 
-            --  Flag an error for a tagged type with defaulted discriminants,
-            --  excluding limited tagged types when compiling for Ada 2012
-            --  (see AI05-0214).
+      Append_Entity (Make_Op_Formal (Typ, Op), Op);
+      Append_Entity (Make_Op_Formal (Typ, Op), Op);
+   end New_Concatenation_Op;
 
-            elsif Is_Tagged_Type (Current_Scope)
-              and then (not Is_Limited_Type (Current_Scope)
-                         or else Ada_Version < Ada_2012)
-              and then Comes_From_Source (N)
-            then
-               --  Note: see similar test in Check_Or_Process_Discriminants, to
-               --  handle the (illegal) case of the completion of an untagged
-               --  view with discriminants with defaults by a tagged full view.
-               --  We skip the check if Discr does not come from source, to
-               --  account for the case of an untagged derived type providing
-               --  defaults for a renamed discriminant from a private untagged
-               --  ancestor with a tagged full view (ACATS B460006).
+   -------------------------
+   -- OK_For_Limited_Init --
+   -------------------------
 
-               if Ada_Version >= Ada_2012 then
-                  Error_Msg_N
-                    ("discriminants of nonlimited tagged type cannot have"
-                       & " defaults",
-                     Expression (Discr));
-               else
-                  Error_Msg_N
-                    ("discriminants of tagged type cannot have defaults",
-                     Expression (Discr));
-               end if;
+   --  ???Check all calls of this, and compare the conditions under which it's
+   --  called.
 
-            else
-               Default_Present := True;
-               Append_Elmt (Expression (Discr), Elist);
+   function OK_For_Limited_Init
+     (Typ : Entity_Id;
+      Exp : Node_Id) return Boolean
+   is
+   begin
+      return Is_CPP_Constructor_Call (Exp)
+        or else (Ada_Version >= Ada_2005
+                  and then not Debug_Flag_Dot_L
+                  and then OK_For_Limited_Init_In_05 (Typ, Exp));
+   end OK_For_Limited_Init;
 
-               --  Tag the defining identifiers for the discriminants with
-               --  their corresponding default expressions from the tree.
+   -------------------------------
+   -- OK_For_Limited_Init_In_05 --
+   -------------------------------
 
-               Set_Discriminant_Default_Value
-                 (Defining_Identifier (Discr), Expression (Discr));
-            end if;
+   function OK_For_Limited_Init_In_05
+     (Typ : Entity_Id;
+      Exp : Node_Id) return Boolean
+   is
+   begin
+      --  An object of a limited interface type can be initialized with any
+      --  expression of a nonlimited descendant type.
 
-            --  In gnatc or gnatprove mode, make sure set Do_Range_Check flag
-            --  gets set unless we can be sure that no range check is required.
+      if Is_Class_Wide_Type (Typ)
+        and then Is_Limited_Interface (Typ)
+        and then not Is_Limited_Type (Etype (Exp))
+      then
+         return True;
+      end if;
 
-            if (GNATprove_Mode or not Expander_Active)
-              and then not
-                Is_In_Range
-                  (Expression (Discr), Discr_Type, Assume_Valid => True)
-            then
-               Set_Do_Range_Check (Expression (Discr));
-            end if;
+      --  Ada 2005 (AI-287, AI-318): Relax the strictness of the front end in
+      --  case of limited aggregates (including extension aggregates), and
+      --  function calls. The function call may have been given in prefixed
+      --  notation, in which case the original node is an indexed component.
+      --  If the function is parameterless, the original node was an explicit
+      --  dereference. The function may also be parameterless, in which case
+      --  the source node is just an identifier.
 
-         --  No default discriminant value given
+      case Nkind (Original_Node (Exp)) is
+         when N_Aggregate | N_Extension_Aggregate | N_Function_Call | N_Op =>
+            return True;
 
-         else
-            Default_Not_Present := True;
-         end if;
+         when N_Identifier =>
+            return Present (Entity (Original_Node (Exp)))
+              and then Ekind (Entity (Original_Node (Exp))) = E_Function;
 
-         --  Ada 2005 (AI-231): Create an Itype that is a duplicate of
-         --  Discr_Type but with the null-exclusion attribute
+         when N_Qualified_Expression =>
+            return
+              OK_For_Limited_Init_In_05
+                (Typ, Expression (Original_Node (Exp)));
 
-         if Ada_Version >= Ada_2005 then
+         --  Ada 2005 (AI-251): If a class-wide interface object is initialized
+         --  with a function call, the expander has rewritten the call into an
+         --  N_Type_Conversion node to force displacement of the pointer to
+         --  reference the component containing the secondary dispatch table.
+         --  Otherwise a type conversion is not a legal context.
+         --  A return statement for a build-in-place function returning a
+         --  synchronized type also introduces an unchecked conversion.
 
-            --  Ada 2005 (AI-231): Static checks
+         when N_Type_Conversion           |
+              N_Unchecked_Type_Conversion =>
+            return not Comes_From_Source (Exp)
+              and then
+                OK_For_Limited_Init_In_05
+                  (Typ, Expression (Original_Node (Exp)));
 
-            if Can_Never_Be_Null (Discr_Type) then
-               Null_Exclusion_Static_Checks (Discr);
+         when N_Indexed_Component     |
+              N_Selected_Component    |
+              N_Explicit_Dereference  =>
+            return Nkind (Exp) = N_Function_Call;
 
-            elsif Is_Access_Type (Discr_Type)
-              and then Null_Exclusion_Present (Discr)
+         --  A use of 'Input is a function call, hence allowed. Normally the
+         --  attribute will be changed to a call, but the attribute by itself
+         --  can occur with -gnatc.
 
-               --  No need to check itypes because in their case this check
-               --  was done at their point of creation
+         when N_Attribute_Reference =>
+            return Attribute_Name (Original_Node (Exp)) = Name_Input;
 
-              and then not Is_Itype (Discr_Type)
-            then
-               if Can_Never_Be_Null (Discr_Type) then
-                  Error_Msg_NE
-                    ("`NOT NULL` not allowed (& already excludes null)",
-                     Discr,
-                     Discr_Type);
-               end if;
+         --  For a case expression, all dependent expressions must be legal
 
-               Set_Etype (Defining_Identifier (Discr),
-                 Create_Null_Excluding_Itype
-                   (T           => Discr_Type,
-                    Related_Nod => Discr));
+         when N_Case_Expression =>
+            declare
+               Alt : Node_Id;
 
-            --  Check for improper null exclusion if the type is otherwise
-            --  legal for a discriminant.
+            begin
+               Alt := First (Alternatives (Original_Node (Exp)));
+               while Present (Alt) loop
+                  if not OK_For_Limited_Init_In_05 (Typ, Expression (Alt)) then
+                     return False;
+                  end if;
 
-            elsif Null_Exclusion_Present (Discr)
-              and then Is_Discrete_Type (Discr_Type)
-            then
-               Error_Msg_N
-                 ("null exclusion can only apply to an access type", Discr);
-            end if;
+                  Next (Alt);
+               end loop;
 
-            --  Ada 2005 (AI-402): access discriminants of nonlimited types
-            --  can't have defaults. Synchronized types, or types that are
-            --  explicitly limited are fine, but special tests apply to derived
-            --  types in generics: in a generic body we have to assume the
-            --  worst, and therefore defaults are not allowed if the parent is
-            --  a generic formal private type (see ACATS B370001).
+               return True;
+            end;
 
-            if Is_Access_Type (Discr_Type) and then Default_Present then
-               if Ekind (Discr_Type) /= E_Anonymous_Access_Type
-                 or else Is_Limited_Record (Current_Scope)
-                 or else Is_Concurrent_Type (Current_Scope)
-                 or else Is_Concurrent_Record_Type (Current_Scope)
-                 or else Ekind (Current_Scope) = E_Limited_Private_Type
-               then
-                  if not Is_Derived_Type (Current_Scope)
-                    or else not Is_Generic_Type (Etype (Current_Scope))
-                    or else not In_Package_Body (Scope (Etype (Current_Scope)))
-                    or else Limited_Present
-                              (Type_Definition (Parent (Current_Scope)))
-                  then
-                     null;
+         --  For an if expression, all dependent expressions must be legal
+
+         when N_If_Expression =>
+            declare
+               Then_Expr : constant Node_Id :=
+                             Next (First (Expressions (Original_Node (Exp))));
+               Else_Expr : constant Node_Id := Next (Then_Expr);
+            begin
+               return OK_For_Limited_Init_In_05 (Typ, Then_Expr)
+                        and then
+                      OK_For_Limited_Init_In_05 (Typ, Else_Expr);
+            end;
+
+         when others =>
+            return False;
+      end case;
+   end OK_For_Limited_Init_In_05;
 
-                  else
-                     Error_Msg_N ("access discriminants of nonlimited types",
-                         Expression (Discr));
-                     Error_Msg_N ("\cannot have defaults", Expression (Discr));
-                  end if;
+   -------------------------------------------
+   -- Ordinary_Fixed_Point_Type_Declaration --
+   -------------------------------------------
 
-               elsif Present (Expression (Discr)) then
-                  Error_Msg_N
-                    ("(Ada 2005) access discriminants of nonlimited types",
-                     Expression (Discr));
-                  Error_Msg_N ("\cannot have defaults", Expression (Discr));
-               end if;
-            end if;
-         end if;
+   procedure Ordinary_Fixed_Point_Type_Declaration
+     (T   : Entity_Id;
+      Def : Node_Id)
+   is
+      Loc           : constant Source_Ptr := Sloc (Def);
+      Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
+      RRS           : constant Node_Id    := Real_Range_Specification (Def);
+      Implicit_Base : Entity_Id;
+      Delta_Val     : Ureal;
+      Small_Val     : Ureal;
+      Low_Val       : Ureal;
+      High_Val      : Ureal;
 
-         --  A discriminant cannot be effectively volatile. This check is only
-         --  relevant when SPARK_Mode is on as it is not standard Ada legality
-         --  rule (SPARK RM 7.1.3(6)).
+   begin
+      Check_Restriction (No_Fixed_Point, Def);
 
-         if SPARK_Mode = On
-           and then Is_Effectively_Volatile (Defining_Identifier (Discr))
-         then
-            Error_Msg_N ("discriminant cannot be volatile", Discr);
-         end if;
+      --  Create implicit base type
 
-         Next (Discr);
-      end loop;
+      Implicit_Base :=
+        Create_Itype (E_Ordinary_Fixed_Point_Type, Parent (Def), T, 'B');
+      Set_Etype (Implicit_Base, Implicit_Base);
 
-      --  An element list consisting of the default expressions of the
-      --  discriminants is constructed in the above loop and used to set
-      --  the Discriminant_Constraint attribute for the type. If an object
-      --  is declared of this (record or task) type without any explicit
-      --  discriminant constraint given, this element list will form the
-      --  actual parameters for the corresponding initialization procedure
-      --  for the type.
+      --  Analyze and process delta expression
 
-      Set_Discriminant_Constraint (Current_Scope, Elist);
-      Set_Stored_Constraint (Current_Scope, No_Elist);
+      Analyze_And_Resolve (Delta_Expr, Any_Real);
 
-      --  Default expressions must be provided either for all or for none
-      --  of the discriminants of a discriminant part. (RM 3.7.1)
+      Check_Delta_Expression (Delta_Expr);
+      Delta_Val := Expr_Value_R (Delta_Expr);
 
-      if Default_Present and then Default_Not_Present then
-         Error_Msg_N
-           ("incomplete specification of defaults for discriminants", N);
-      end if;
+      Set_Delta_Value (Implicit_Base, Delta_Val);
 
-      --  The use of the name of a discriminant is not allowed in default
-      --  expressions of a discriminant part if the specification of the
-      --  discriminant is itself given in the discriminant part. (RM 3.7.1)
+      --  Compute default small from given delta, which is the largest power
+      --  of two that does not exceed the given delta value.
 
-      --  To detect this, the discriminant names are entered initially with an
-      --  Ekind of E_Void (which is the default Ekind given by Enter_Name). Any
-      --  attempt to use a void entity (for example in an expression that is
-      --  type-checked) produces the error message: premature usage. Now after
-      --  completing the semantic analysis of the discriminant part, we can set
-      --  the Ekind of all the discriminants appropriately.
+      declare
+         Tmp   : Ureal;
+         Scale : Int;
 
-      Discr := First (Discriminant_Specifications (N));
-      Discr_Number := Uint_1;
-      while Present (Discr) loop
-         Id := Defining_Identifier (Discr);
-         Set_Ekind (Id, E_Discriminant);
-         Init_Component_Location (Id);
-         Init_Esize (Id);
-         Set_Discriminant_Number (Id, Discr_Number);
+      begin
+         Tmp := Ureal_1;
+         Scale := 0;
 
-         --  Make sure this is always set, even in illegal programs
+         if Delta_Val < Ureal_1 then
+            while Delta_Val < Tmp loop
+               Tmp := Tmp / Ureal_2;
+               Scale := Scale + 1;
+            end loop;
 
-         Set_Corresponding_Discriminant (Id, Empty);
+         else
+            loop
+               Tmp := Tmp * Ureal_2;
+               exit when Tmp > Delta_Val;
+               Scale := Scale - 1;
+            end loop;
+         end if;
 
-         --  Initialize the Original_Record_Component to the entity itself.
-         --  Inherit_Components will propagate the right value to
-         --  discriminants in derived record types.
+         Small_Val := UR_From_Components (Uint_1, UI_From_Int (Scale), 2);
+      end;
 
-         Set_Original_Record_Component (Id, Id);
+      Set_Small_Value (Implicit_Base, Small_Val);
 
-         --  Create the discriminal for the discriminant
+      --  If no range was given, set a dummy range
 
-         Build_Discriminal (Id);
+      if RRS <= Empty_Or_Error then
+         Low_Val  := -Small_Val;
+         High_Val := Small_Val;
 
-         Next (Discr);
-         Discr_Number := Discr_Number + 1;
-      end loop;
+      --  Otherwise analyze and process given range
 
-      Set_Has_Discriminants (Current_Scope);
-   end Process_Discriminants;
+      else
+         declare
+            Low  : constant Node_Id := Low_Bound  (RRS);
+            High : constant Node_Id := High_Bound (RRS);
 
-   -----------------------
-   -- Process_Full_View --
-   -----------------------
+         begin
+            Analyze_And_Resolve (Low, Any_Real);
+            Analyze_And_Resolve (High, Any_Real);
+            Check_Real_Bound (Low);
+            Check_Real_Bound (High);
 
-   procedure Process_Full_View (N : Node_Id; Full_T, Priv_T : Entity_Id) is
-      Priv_Parent : Entity_Id;
-      Full_Parent : Entity_Id;
-      Full_Indic  : Node_Id;
+            --  Obtain and set the range
 
-      procedure Collect_Implemented_Interfaces
-        (Typ    : Entity_Id;
-         Ifaces : Elist_Id);
-      --  Ada 2005: Gather all the interfaces that Typ directly or
-      --  inherently implements. Duplicate entries are not added to
-      --  the list Ifaces.
+            Low_Val  := Expr_Value_R (Low);
+            High_Val := Expr_Value_R (High);
 
-      ------------------------------------
-      -- Collect_Implemented_Interfaces --
-      ------------------------------------
+            if Low_Val > High_Val then
+               Error_Msg_NE ("??fixed point type& has null range", Def, T);
+            end if;
+         end;
+      end if;
 
-      procedure Collect_Implemented_Interfaces
-        (Typ    : Entity_Id;
-         Ifaces : Elist_Id)
-      is
-         Iface      : Entity_Id;
-         Iface_Elmt : Elmt_Id;
+      --  The range for both the implicit base and the declared first subtype
+      --  cannot be set yet, so we use the special routine Set_Fixed_Range to
+      --  set a temporary range in place. Note that the bounds of the base
+      --  type will be widened to be symmetrical and to fill the available
+      --  bits when the type is frozen.
 
-      begin
-         --  Abstract interfaces are only associated with tagged record types
+      --  We could do this with all discrete types, and probably should, but
+      --  we absolutely have to do it for fixed-point, since the end-points
+      --  of the range and the size are determined by the small value, which
+      --  could be reset before the freeze point.
 
-         if not Is_Tagged_Type (Typ)
-           or else not Is_Record_Type (Typ)
-         then
-            return;
-         end if;
+      Set_Fixed_Range (Implicit_Base, Loc, Low_Val, High_Val);
+      Set_Fixed_Range (T, Loc, Low_Val, High_Val);
 
-         --  Recursively climb to the ancestors
+      --  Complete definition of first subtype. The inheritance of the rep item
+      --  chain ensures that SPARK-related pragmas are not clobbered when the
+      --  ordinary fixed point type acts as a full view of a private type.
+
+      Set_Ekind              (T, E_Ordinary_Fixed_Point_Subtype);
+      Set_Etype              (T, Implicit_Base);
+      Init_Size_Align        (T);
+      Inherit_Rep_Item_Chain (T, Implicit_Base);
+      Set_Small_Value        (T, Small_Val);
+      Set_Delta_Value        (T, Delta_Val);
+      Set_Is_Constrained     (T);
+   end Ordinary_Fixed_Point_Type_Declaration;
 
-         if Etype (Typ) /= Typ
+   ----------------------------------
+   -- Preanalyze_Assert_Expression --
+   ----------------------------------
 
-            --  Protect the frontend against wrong cyclic declarations like:
+   procedure Preanalyze_Assert_Expression (N : Node_Id; T : Entity_Id) is
+   begin
+      In_Assertion_Expr := In_Assertion_Expr + 1;
+      Preanalyze_Spec_Expression (N, T);
+      In_Assertion_Expr := In_Assertion_Expr - 1;
+   end Preanalyze_Assert_Expression;
 
-            --     type B is new A with private;
-            --     type C is new A with private;
-            --  private
-            --     type B is new C with null record;
-            --     type C is new B with null record;
+   -----------------------------------
+   -- Preanalyze_Default_Expression --
+   -----------------------------------
 
-           and then Etype (Typ) /= Priv_T
-           and then Etype (Typ) /= Full_T
-         then
-            --  Keep separate the management of private type declarations
+   procedure Preanalyze_Default_Expression (N : Node_Id; T : Entity_Id) is
+      Save_In_Default_Expr : constant Boolean := In_Default_Expr;
+   begin
+      In_Default_Expr := True;
+      Preanalyze_Spec_Expression (N, T);
+      In_Default_Expr := Save_In_Default_Expr;
+   end Preanalyze_Default_Expression;
 
-            if Ekind (Typ) = E_Record_Type_With_Private then
+   --------------------------------
+   -- Preanalyze_Spec_Expression --
+   --------------------------------
 
-               --  Handle the following illegal usage:
-               --      type Private_Type is tagged private;
-               --   private
-               --      type Private_Type is new Type_Implementing_Iface;
+   procedure Preanalyze_Spec_Expression (N : Node_Id; T : Entity_Id) is
+      Save_In_Spec_Expression : constant Boolean := In_Spec_Expression;
+   begin
+      In_Spec_Expression := True;
+      Preanalyze_And_Resolve (N, T);
+      In_Spec_Expression := Save_In_Spec_Expression;
+   end Preanalyze_Spec_Expression;
 
-               if Present (Full_View (Typ))
-                 and then Etype (Typ) /= Full_View (Typ)
-               then
-                  if Is_Interface (Etype (Typ)) then
-                     Append_Unique_Elmt (Etype (Typ), Ifaces);
-                  end if;
+   ----------------------------------------
+   -- Prepare_Private_Subtype_Completion --
+   ----------------------------------------
 
-                  Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
-               end if;
+   procedure Prepare_Private_Subtype_Completion
+     (Id          : Entity_Id;
+      Related_Nod : Node_Id)
+   is
+      Id_B   : constant Entity_Id := Base_Type (Id);
+      Full_B : Entity_Id := Full_View (Id_B);
+      Full   : Entity_Id;
 
-            --  Non-private types
+   begin
+      if Present (Full_B) then
 
-            else
-               if Is_Interface (Etype (Typ)) then
-                  Append_Unique_Elmt (Etype (Typ), Ifaces);
-               end if;
+         --  Get to the underlying full view if necessary
 
-               Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
-            end if;
+         if Is_Private_Type (Full_B)
+           and then Present (Underlying_Full_View (Full_B))
+         then
+            Full_B := Underlying_Full_View (Full_B);
          end if;
 
-         --  Handle entities in the list of abstract interfaces
+         --  The Base_Type is already completed, we can complete the subtype
+         --  now. We have to create a new entity with the same name, Thus we
+         --  can't use Create_Itype.
 
-         if Present (Interfaces (Typ)) then
-            Iface_Elmt := First_Elmt (Interfaces (Typ));
-            while Present (Iface_Elmt) loop
-               Iface := Node (Iface_Elmt);
+         Full := Make_Defining_Identifier (Sloc (Id), Chars (Id));
+         Set_Is_Itype (Full);
+         Set_Associated_Node_For_Itype (Full, Related_Nod);
+         Complete_Private_Subtype (Id, Full, Full_B, Related_Nod);
+      end if;
 
-               pragma Assert (Is_Interface (Iface));
+      --  The parent subtype may be private, but the base might not, in some
+      --  nested instances. In that case, the subtype does not need to be
+      --  exchanged. It would still be nice to make private subtypes and their
+      --  bases consistent at all times ???
 
-               if not Contain_Interface (Iface, Ifaces) then
-                  Append_Elmt (Iface, Ifaces);
-                  Collect_Implemented_Interfaces (Iface, Ifaces);
-               end if;
+      if Is_Private_Type (Id_B) then
+         Append_Elmt (Id, Private_Dependents (Id_B));
+      end if;
+   end Prepare_Private_Subtype_Completion;
 
-               Next_Elmt (Iface_Elmt);
-            end loop;
-         end if;
-      end Collect_Implemented_Interfaces;
+   ---------------------------
+   -- Process_Discriminants --
+   ---------------------------
 
-   --  Start of processing for Process_Full_View
+   procedure Process_Discriminants
+     (N    : Node_Id;
+      Prev : Entity_Id := Empty)
+   is
+      Elist               : constant Elist_Id := New_Elmt_List;
+      Id                  : Node_Id;
+      Discr               : Node_Id;
+      Discr_Number        : Uint;
+      Discr_Type          : Entity_Id;
+      Default_Present     : Boolean := False;
+      Default_Not_Present : Boolean := False;
 
    begin
-      --  First some sanity checks that must be done after semantic
-      --  decoration of the full view and thus cannot be placed with other
-      --  similar checks in Find_Type_Name
+      --  A composite type other than an array type can have discriminants.
+      --  On entry, the current scope is the composite type.
 
-      if not Is_Limited_Type (Priv_T)
-        and then (Is_Limited_Type (Full_T)
-                   or else Is_Limited_Composite (Full_T))
-      then
-         if In_Instance then
-            null;
-         else
-            Error_Msg_N
-              ("completion of nonlimited type cannot be limited", Full_T);
-            Explain_Limited_Type (Full_T, Full_T);
-         end if;
+      --  The discriminants are initially entered into the scope of the type
+      --  via Enter_Name with the default Ekind of E_Void to prevent premature
+      --  use, as explained at the end of this procedure.
 
-      elsif Is_Abstract_Type (Full_T)
-        and then not Is_Abstract_Type (Priv_T)
-      then
-         Error_Msg_N
-           ("completion of nonabstract type cannot be abstract", Full_T);
+      Discr := First (Discriminant_Specifications (N));
+      while Present (Discr) loop
+         Enter_Name (Defining_Identifier (Discr));
 
-      elsif Is_Tagged_Type (Priv_T)
-        and then Is_Limited_Type (Priv_T)
-        and then not Is_Limited_Type (Full_T)
-      then
-         --  If pragma CPP_Class was applied to the private declaration
-         --  propagate the limitedness to the full-view
+         --  For navigation purposes we add a reference to the discriminant
+         --  in the entity for the type. If the current declaration is a
+         --  completion, place references on the partial view. Otherwise the
+         --  type is the current scope.
 
-         if Is_CPP_Class (Priv_T) then
-            Set_Is_Limited_Record (Full_T);
+         if Present (Prev) then
 
-         --  GNAT allow its own definition of Limited_Controlled to disobey
-         --  this rule in order in ease the implementation. This test is safe
-         --  because Root_Controlled is defined in a child of System that
-         --  normal programs are not supposed to use.
+            --  The references go on the partial view, if present. If the
+            --  partial view has discriminants, the references have been
+            --  generated already.
 
-         elsif Is_RTE (Etype (Full_T), RE_Root_Controlled) then
-            Set_Is_Limited_Composite (Full_T);
+            if not Has_Discriminants (Prev) then
+               Generate_Reference (Prev, Defining_Identifier (Discr), 'd');
+            end if;
          else
-            Error_Msg_N
-              ("completion of limited tagged type must be limited", Full_T);
+            Generate_Reference
+              (Current_Scope, Defining_Identifier (Discr), 'd');
          end if;
 
-      elsif Is_Generic_Type (Priv_T) then
-         Error_Msg_N ("generic type cannot have a completion", Full_T);
-      end if;
+         if Nkind (Discriminant_Type (Discr)) = N_Access_Definition then
+            Discr_Type := Access_Definition (Discr, Discriminant_Type (Discr));
 
-      --  Check that ancestor interfaces of private and full views are
-      --  consistent. We omit this check for synchronized types because
-      --  they are performed on the corresponding record type when frozen.
+            --  Ada 2005 (AI-254)
 
-      if Ada_Version >= Ada_2005
-        and then Is_Tagged_Type (Priv_T)
-        and then Is_Tagged_Type (Full_T)
-        and then not Is_Concurrent_Type (Full_T)
-      then
-         declare
-            Iface         : Entity_Id;
-            Priv_T_Ifaces : constant Elist_Id := New_Elmt_List;
-            Full_T_Ifaces : constant Elist_Id := New_Elmt_List;
+            if Present (Access_To_Subprogram_Definition
+                         (Discriminant_Type (Discr)))
+              and then Protected_Present (Access_To_Subprogram_Definition
+                                           (Discriminant_Type (Discr)))
+            then
+               Discr_Type :=
+                 Replace_Anonymous_Access_To_Protected_Subprogram (Discr);
+            end if;
 
-         begin
-            Collect_Implemented_Interfaces (Priv_T, Priv_T_Ifaces);
-            Collect_Implemented_Interfaces (Full_T, Full_T_Ifaces);
+         else
+            Find_Type (Discriminant_Type (Discr));
+            Discr_Type := Etype (Discriminant_Type (Discr));
 
-            --  Ada 2005 (AI-251): The partial view shall be a descendant of
-            --  an interface type if and only if the full type is descendant
-            --  of the interface type (AARM 7.3 (7.3/2)).
+            if Error_Posted (Discriminant_Type (Discr)) then
+               Discr_Type := Any_Type;
+            end if;
+         end if;
 
-            Iface := Find_Hidden_Interface (Priv_T_Ifaces, Full_T_Ifaces);
+         --  Handling of discriminants that are access types
 
-            if Present (Iface) then
-               Error_Msg_NE
-                 ("interface in partial view& not implemented by full type "
-                  & "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
-            end if;
+         if Is_Access_Type (Discr_Type) then
 
-            Iface := Find_Hidden_Interface (Full_T_Ifaces, Priv_T_Ifaces);
+            --  Ada 2005 (AI-230): Access discriminant allowed in non-
+            --  limited record types
 
-            if Present (Iface) then
-               Error_Msg_NE
-                 ("interface & not implemented by partial view "
-                  & "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
+            if Ada_Version < Ada_2005 then
+               Check_Access_Discriminant_Requires_Limited
+                 (Discr, Discriminant_Type (Discr));
             end if;
-         end;
-      end if;
 
-      if Is_Tagged_Type (Priv_T)
-        and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
-        and then Is_Derived_Type (Full_T)
-      then
-         Priv_Parent := Etype (Priv_T);
+            if Ada_Version = Ada_83 and then Comes_From_Source (Discr) then
+               Error_Msg_N
+                 ("(Ada 83) access discriminant not allowed", Discr);
+            end if;
 
-         --  The full view of a private extension may have been transformed
-         --  into an unconstrained derived type declaration and a subtype
-         --  declaration (see build_derived_record_type for details).
+         --  If not access type, must be a discrete type
 
-         if Nkind (N) = N_Subtype_Declaration then
-            Full_Indic  := Subtype_Indication (N);
-            Full_Parent := Etype (Base_Type (Full_T));
-         else
-            Full_Indic  := Subtype_Indication (Type_Definition (N));
-            Full_Parent := Etype (Full_T);
+         elsif not Is_Discrete_Type (Discr_Type) then
+            Error_Msg_N
+              ("discriminants must have a discrete or access type",
+               Discriminant_Type (Discr));
          end if;
 
-         --  Check that the parent type of the full type is a descendant of
-         --  the ancestor subtype given in the private extension. If either
-         --  entity has an Etype equal to Any_Type then we had some previous
-         --  error situation [7.3(8)].
+         Set_Etype (Defining_Identifier (Discr), Discr_Type);
 
-         if Priv_Parent = Any_Type or else Full_Parent = Any_Type then
-            return;
+         --  If a discriminant specification includes the assignment compound
+         --  delimiter followed by an expression, the expression is the default
+         --  expression of the discriminant; the default expression must be of
+         --  the type of the discriminant. (RM 3.7.1) Since this expression is
+         --  a default expression, we do the special preanalysis, since this
+         --  expression does not freeze (see section "Handling of Default and
+         --  Per-Object Expressions" in spec of package Sem).
 
-         --  Ada 2005 (AI-251): Interfaces in the full type can be given in
-         --  any order. Therefore we don't have to check that its parent must
-         --  be a descendant of the parent of the private type declaration.
+         if Present (Expression (Discr)) then
+            Preanalyze_Spec_Expression (Expression (Discr), Discr_Type);
 
-         elsif Is_Interface (Priv_Parent)
-           and then Is_Interface (Full_Parent)
-         then
-            null;
+            --  Legaity checks
 
-         --  Ada 2005 (AI-251): If the parent of the private type declaration
-         --  is an interface there is no need to check that it is an ancestor
-         --  of the associated full type declaration. The required tests for
-         --  this case are performed by Build_Derived_Record_Type.
+            if Nkind (N) = N_Formal_Type_Declaration then
+               Error_Msg_N
+                 ("discriminant defaults not allowed for formal type",
+                  Expression (Discr));
 
-         elsif not Is_Interface (Base_Type (Priv_Parent))
-           and then not Is_Ancestor (Base_Type (Priv_Parent), Full_Parent)
-         then
-            Error_Msg_N
-              ("parent of full type must descend from parent"
-                  & " of private extension", Full_Indic);
+            --  Flag an error for a tagged type with defaulted discriminants,
+            --  excluding limited tagged types when compiling for Ada 2012
+            --  (see AI05-0214).
 
-         --  First check a formal restriction, and then proceed with checking
-         --  Ada rules. Since the formal restriction is not a serious error, we
-         --  don't prevent further error detection for this check, hence the
-         --  ELSE.
+            elsif Is_Tagged_Type (Current_Scope)
+              and then (not Is_Limited_Type (Current_Scope)
+                         or else Ada_Version < Ada_2012)
+              and then Comes_From_Source (N)
+            then
+               --  Note: see similar test in Check_Or_Process_Discriminants, to
+               --  handle the (illegal) case of the completion of an untagged
+               --  view with discriminants with defaults by a tagged full view.
+               --  We skip the check if Discr does not come from source, to
+               --  account for the case of an untagged derived type providing
+               --  defaults for a renamed discriminant from a private untagged
+               --  ancestor with a tagged full view (ACATS B460006).
 
-         else
+               if Ada_Version >= Ada_2012 then
+                  Error_Msg_N
+                    ("discriminants of nonlimited tagged type cannot have"
+                       & " defaults",
+                     Expression (Discr));
+               else
+                  Error_Msg_N
+                    ("discriminants of tagged type cannot have defaults",
+                     Expression (Discr));
+               end if;
 
-            --  In formal mode, when completing a private extension the type
-            --  named in the private part must be exactly the same as that
-            --  named in the visible part.
+            else
+               Default_Present := True;
+               Append_Elmt (Expression (Discr), Elist);
 
-            if Priv_Parent /= Full_Parent then
-               Error_Msg_Name_1 := Chars (Priv_Parent);
-               Check_SPARK_Restriction ("% expected", Full_Indic);
+               --  Tag the defining identifiers for the discriminants with
+               --  their corresponding default expressions from the tree.
+
+               Set_Discriminant_Default_Value
+                 (Defining_Identifier (Discr), Expression (Discr));
+            end if;
+
+            --  In gnatc or gnatprove mode, make sure set Do_Range_Check flag
+            --  gets set unless we can be sure that no range check is required.
+
+            if (GNATprove_Mode or not Expander_Active)
+              and then not
+                Is_In_Range
+                  (Expression (Discr), Discr_Type, Assume_Valid => True)
+            then
+               Set_Do_Range_Check (Expression (Discr));
             end if;
 
-            --  Check the rules of 7.3(10): if the private extension inherits
-            --  known discriminants, then the full type must also inherit those
-            --  discriminants from the same (ancestor) type, and the parent
-            --  subtype of the full type must be constrained if and only if
-            --  the ancestor subtype of the private extension is constrained.
+         --  No default discriminant value given
 
-            if No (Discriminant_Specifications (Parent (Priv_T)))
-              and then not Has_Unknown_Discriminants (Priv_T)
-              and then Has_Discriminants (Base_Type (Priv_Parent))
-            then
-               declare
-                  Priv_Indic  : constant Node_Id :=
-                                  Subtype_Indication (Parent (Priv_T));
+         else
+            Default_Not_Present := True;
+         end if;
 
-                  Priv_Constr : constant Boolean :=
-                                  Is_Constrained (Priv_Parent)
-                                    or else
-                                      Nkind (Priv_Indic) = N_Subtype_Indication
-                                    or else
-                                      Is_Constrained (Entity (Priv_Indic));
+         --  Ada 2005 (AI-231): Create an Itype that is a duplicate of
+         --  Discr_Type but with the null-exclusion attribute
 
-                  Full_Constr : constant Boolean :=
-                                  Is_Constrained (Full_Parent)
-                                    or else
-                                      Nkind (Full_Indic) = N_Subtype_Indication
-                                    or else
-                                      Is_Constrained (Entity (Full_Indic));
+         if Ada_Version >= Ada_2005 then
 
-                  Priv_Discr : Entity_Id;
-                  Full_Discr : Entity_Id;
+            --  Ada 2005 (AI-231): Static checks
 
-               begin
-                  Priv_Discr := First_Discriminant (Priv_Parent);
-                  Full_Discr := First_Discriminant (Full_Parent);
-                  while Present (Priv_Discr) and then Present (Full_Discr) loop
-                     if Original_Record_Component (Priv_Discr) =
-                        Original_Record_Component (Full_Discr)
-                       or else
-                         Corresponding_Discriminant (Priv_Discr) =
-                         Corresponding_Discriminant (Full_Discr)
-                     then
-                        null;
-                     else
-                        exit;
-                     end if;
+            if Can_Never_Be_Null (Discr_Type) then
+               Null_Exclusion_Static_Checks (Discr);
 
-                     Next_Discriminant (Priv_Discr);
-                     Next_Discriminant (Full_Discr);
-                  end loop;
+            elsif Is_Access_Type (Discr_Type)
+              and then Null_Exclusion_Present (Discr)
 
-                  if Present (Priv_Discr) or else Present (Full_Discr) then
-                     Error_Msg_N
-                       ("full view must inherit discriminants of the parent"
-                        & " type used in the private extension", Full_Indic);
+               --  No need to check itypes because in their case this check
+               --  was done at their point of creation
 
-                  elsif Priv_Constr and then not Full_Constr then
-                     Error_Msg_N
-                       ("parent subtype of full type must be constrained",
-                        Full_Indic);
+              and then not Is_Itype (Discr_Type)
+            then
+               if Can_Never_Be_Null (Discr_Type) then
+                  Error_Msg_NE
+                    ("`NOT NULL` not allowed (& already excludes null)",
+                     Discr,
+                     Discr_Type);
+               end if;
 
-                  elsif Full_Constr and then not Priv_Constr then
-                     Error_Msg_N
-                       ("parent subtype of full type must be unconstrained",
-                        Full_Indic);
-                  end if;
-               end;
+               Set_Etype (Defining_Identifier (Discr),
+                 Create_Null_Excluding_Itype
+                   (T           => Discr_Type,
+                    Related_Nod => Discr));
 
-               --  Check the rules of 7.3(12): if a partial view has neither
-               --  known or unknown discriminants, then the full type
-               --  declaration shall define a definite subtype.
+            --  Check for improper null exclusion if the type is otherwise
+            --  legal for a discriminant.
 
-            elsif      not Has_Unknown_Discriminants (Priv_T)
-              and then not Has_Discriminants (Priv_T)
-              and then not Is_Constrained (Full_T)
+            elsif Null_Exclusion_Present (Discr)
+              and then Is_Discrete_Type (Discr_Type)
             then
                Error_Msg_N
-                 ("full view must define a constrained type if partial view"
-                  & " has no discriminants", Full_T);
+                 ("null exclusion can only apply to an access type", Discr);
             end if;
 
-            --  ??????? Do we implement the following properly ?????
-            --  If the ancestor subtype of a private extension has constrained
-            --  discriminants, then the parent subtype of the full view shall
-            --  impose a statically matching constraint on those discriminants
-            --  [7.3(13)].
-         end if;
+            --  Ada 2005 (AI-402): access discriminants of nonlimited types
+            --  can't have defaults. Synchronized types, or types that are
+            --  explicitly limited are fine, but special tests apply to derived
+            --  types in generics: in a generic body we have to assume the
+            --  worst, and therefore defaults are not allowed if the parent is
+            --  a generic formal private type (see ACATS B370001).
 
-      else
-         --  For untagged types, verify that a type without discriminants is
-         --  not completed with an unconstrained type. A separate error message
-         --  is produced if the full type has defaulted discriminants.
+            if Is_Access_Type (Discr_Type) and then Default_Present then
+               if Ekind (Discr_Type) /= E_Anonymous_Access_Type
+                 or else Is_Limited_Record (Current_Scope)
+                 or else Is_Concurrent_Type (Current_Scope)
+                 or else Is_Concurrent_Record_Type (Current_Scope)
+                 or else Ekind (Current_Scope) = E_Limited_Private_Type
+               then
+                  if not Is_Derived_Type (Current_Scope)
+                    or else not Is_Generic_Type (Etype (Current_Scope))
+                    or else not In_Package_Body (Scope (Etype (Current_Scope)))
+                    or else Limited_Present
+                              (Type_Definition (Parent (Current_Scope)))
+                  then
+                     null;
 
-         if not Is_Indefinite_Subtype (Priv_T)
-           and then Is_Indefinite_Subtype (Full_T)
-         then
-            Error_Msg_Sloc := Sloc (Parent (Priv_T));
-            Error_Msg_NE
-              ("full view of& not compatible with declaration#",
-               Full_T, Priv_T);
+                  else
+                     Error_Msg_N
+                       ("access discriminants of nonlimited types cannot "
+                        & "have defaults", Expression (Discr));
+                  end if;
 
-            if not Is_Tagged_Type (Full_T) then
-               Error_Msg_N
-                 ("\one is constrained, the other unconstrained", Full_T);
+               elsif Present (Expression (Discr)) then
+                  Error_Msg_N
+                    ("(Ada 2005) access discriminants of nonlimited types "
+                     & "cannot have defaults", Expression (Discr));
+               end if;
             end if;
          end if;
-      end if;
 
-      --  AI-419: verify that the use of "limited" is consistent
-
-      declare
-         Orig_Decl : constant Node_Id := Original_Node (N);
+         --  A discriminant cannot be effectively volatile. This check is only
+         --  relevant when SPARK_Mode is on as it is not standard Ada legality
+         --  rule (SPARK RM 7.1.3(6)).
 
-      begin
-         if Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
-           and then not Limited_Present (Parent (Priv_T))
-           and then not Synchronized_Present (Parent (Priv_T))
-           and then Nkind (Orig_Decl) = N_Full_Type_Declaration
-           and then Nkind
-             (Type_Definition (Orig_Decl)) = N_Derived_Type_Definition
-           and then Limited_Present (Type_Definition (Orig_Decl))
+         if SPARK_Mode = On
+           and then Is_Effectively_Volatile (Defining_Identifier (Discr))
          then
-            Error_Msg_N
-              ("full view of non-limited extension cannot be limited", N);
+            Error_Msg_N ("discriminant cannot be volatile", Discr);
          end if;
-      end;
 
-      --  Ada 2005 (AI-443): A synchronized private extension must be
-      --  completed by a task or protected type.
+         Next (Discr);
+      end loop;
 
-      if Ada_Version >= Ada_2005
-        and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
-        and then Synchronized_Present (Parent (Priv_T))
-        and then not Is_Concurrent_Type (Full_T)
-      then
-         Error_Msg_N ("full view of synchronized extension must " &
-                      "be synchronized type", N);
+      --  An element list consisting of the default expressions of the
+      --  discriminants is constructed in the above loop and used to set
+      --  the Discriminant_Constraint attribute for the type. If an object
+      --  is declared of this (record or task) type without any explicit
+      --  discriminant constraint given, this element list will form the
+      --  actual parameters for the corresponding initialization procedure
+      --  for the type.
+
+      Set_Discriminant_Constraint (Current_Scope, Elist);
+      Set_Stored_Constraint (Current_Scope, No_Elist);
+
+      --  Default expressions must be provided either for all or for none
+      --  of the discriminants of a discriminant part. (RM 3.7.1)
+
+      if Default_Present and then Default_Not_Present then
+         Error_Msg_N
+           ("incomplete specification of defaults for discriminants", N);
       end if;
 
-      --  Ada 2005 AI-363: if the full view has discriminants with
-      --  defaults, it is illegal to declare constrained access subtypes
-      --  whose designated type is the current type. This allows objects
-      --  of the type that are declared in the heap to be unconstrained.
+      --  The use of the name of a discriminant is not allowed in default
+      --  expressions of a discriminant part if the specification of the
+      --  discriminant is itself given in the discriminant part. (RM 3.7.1)
+
+      --  To detect this, the discriminant names are entered initially with an
+      --  Ekind of E_Void (which is the default Ekind given by Enter_Name). Any
+      --  attempt to use a void entity (for example in an expression that is
+      --  type-checked) produces the error message: premature usage. Now after
+      --  completing the semantic analysis of the discriminant part, we can set
+      --  the Ekind of all the discriminants appropriately.
+
+      Discr := First (Discriminant_Specifications (N));
+      Discr_Number := Uint_1;
+      while Present (Discr) loop
+         Id := Defining_Identifier (Discr);
+         Set_Ekind (Id, E_Discriminant);
+         Init_Component_Location (Id);
+         Init_Esize (Id);
+         Set_Discriminant_Number (Id, Discr_Number);
+
+         --  Make sure this is always set, even in illegal programs
+
+         Set_Corresponding_Discriminant (Id, Empty);
+
+         --  Initialize the Original_Record_Component to the entity itself.
+         --  Inherit_Components will propagate the right value to
+         --  discriminants in derived record types.
+
+         Set_Original_Record_Component (Id, Id);
+
+         --  Create the discriminal for the discriminant
+
+         Build_Discriminal (Id);
+
+         Next (Discr);
+         Discr_Number := Discr_Number + 1;
+      end loop;
+
+      Set_Has_Discriminants (Current_Scope);
+   end Process_Discriminants;
+
+   -----------------------
+   -- Process_Full_View --
+   -----------------------
+
+   procedure Process_Full_View (N : Node_Id; Full_T, Priv_T : Entity_Id) is
+      procedure Collect_Implemented_Interfaces
+        (Typ    : Entity_Id;
+         Ifaces : Elist_Id);
+      --  Ada 2005: Gather all the interfaces that Typ directly or
+      --  inherently implements. Duplicate entries are not added to
+      --  the list Ifaces.
+
+      ------------------------------------
+      -- Collect_Implemented_Interfaces --
+      ------------------------------------
+
+      procedure Collect_Implemented_Interfaces
+        (Typ    : Entity_Id;
+         Ifaces : Elist_Id)
+      is
+         Iface      : Entity_Id;
+         Iface_Elmt : Elmt_Id;
 
-      if not Has_Unknown_Discriminants (Priv_T)
-        and then not Has_Discriminants (Priv_T)
-        and then Has_Discriminants (Full_T)
-        and then
-          Present (Discriminant_Default_Value (First_Discriminant (Full_T)))
-      then
-         Set_Has_Constrained_Partial_View (Full_T);
-         Set_Has_Constrained_Partial_View (Priv_T);
-      end if;
+      begin
+         --  Abstract interfaces are only associated with tagged record types
 
-      --  Create a full declaration for all its subtypes recorded in
-      --  Private_Dependents and swap them similarly to the base type. These
-      --  are subtypes that have been define before the full declaration of
-      --  the private type. We also swap the entry in Private_Dependents list
-      --  so we can properly restore the private view on exit from the scope.
+         if not Is_Tagged_Type (Typ) or else not Is_Record_Type (Typ) then
+            return;
+         end if;
 
-      declare
-         Priv_Elmt : Elmt_Id;
-         Priv_Scop : Entity_Id;
-         Priv      : Entity_Id;
-         Full      : Entity_Id;
+         --  Recursively climb to the ancestors
 
-      begin
-         Priv_Elmt := First_Elmt (Private_Dependents (Priv_T));
-         while Present (Priv_Elmt) loop
-            Priv := Node (Priv_Elmt);
-            Priv_Scop := Scope (Priv);
+         if Etype (Typ) /= Typ
 
-            if Ekind_In (Priv, E_Private_Subtype,
-                               E_Limited_Private_Subtype,
-                               E_Record_Subtype_With_Private)
-            then
-               Full := Make_Defining_Identifier (Sloc (Priv), Chars (Priv));
-               Set_Is_Itype (Full);
-               Set_Parent (Full, Parent (Priv));
-               Set_Associated_Node_For_Itype (Full, N);
+            --  Protect the frontend against wrong cyclic declarations like:
 
-               --  Now we need to complete the private subtype, but since the
-               --  base type has already been swapped, we must also swap the
-               --  subtypes (and thus, reverse the arguments in the call to
-               --  Complete_Private_Subtype). Also note that we may need to
-               --  re-establish the scope of the private subtype.
+            --     type B is new A with private;
+            --     type C is new A with private;
+            --  private
+            --     type B is new C with null record;
+            --     type C is new B with null record;
 
-               Copy_And_Swap (Priv, Full);
+           and then Etype (Typ) /= Priv_T
+           and then Etype (Typ) /= Full_T
+         then
+            --  Keep separate the management of private type declarations
 
-               if not In_Open_Scopes (Priv_Scop) then
-                  Push_Scope (Priv_Scop);
+            if Ekind (Typ) = E_Record_Type_With_Private then
 
-               else
-                  --  Reset Priv_Scop to Empty to indicate no scope was pushed
+               --  Handle the following illegal usage:
+               --      type Private_Type is tagged private;
+               --   private
+               --      type Private_Type is new Type_Implementing_Iface;
 
-                  Priv_Scop := Empty;
+               if Present (Full_View (Typ))
+                 and then Etype (Typ) /= Full_View (Typ)
+               then
+                  if Is_Interface (Etype (Typ)) then
+                     Append_Unique_Elmt (Etype (Typ), Ifaces);
+                  end if;
+
+                  Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
                end if;
 
-               Complete_Private_Subtype (Full, Priv, Full_T, N);
+            --  Non-private types
 
-               if Present (Priv_Scop) then
-                  Pop_Scope;
+            else
+               if Is_Interface (Etype (Typ)) then
+                  Append_Unique_Elmt (Etype (Typ), Ifaces);
                end if;
 
-               Replace_Elmt (Priv_Elmt, Full);
+               Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
             end if;
+         end if;
 
-            Next_Elmt (Priv_Elmt);
-         end loop;
-      end;
+         --  Handle entities in the list of abstract interfaces
 
-      --  If the private view was tagged, copy the new primitive operations
-      --  from the private view to the full view.
+         if Present (Interfaces (Typ)) then
+            Iface_Elmt := First_Elmt (Interfaces (Typ));
+            while Present (Iface_Elmt) loop
+               Iface := Node (Iface_Elmt);
 
-      if Is_Tagged_Type (Full_T) then
-         declare
-            Disp_Typ  : Entity_Id;
-            Full_List : Elist_Id;
-            Prim      : Entity_Id;
-            Prim_Elmt : Elmt_Id;
-            Priv_List : Elist_Id;
+               pragma Assert (Is_Interface (Iface));
 
-            function Contains
-              (E : Entity_Id;
-               L : Elist_Id) return Boolean;
-            --  Determine whether list L contains element E
+               if not Contain_Interface (Iface, Ifaces) then
+                  Append_Elmt (Iface, Ifaces);
+                  Collect_Implemented_Interfaces (Iface, Ifaces);
+               end if;
 
-            --------------
-            -- Contains --
-            --------------
+               Next_Elmt (Iface_Elmt);
+            end loop;
+         end if;
+      end Collect_Implemented_Interfaces;
 
-            function Contains
-              (E : Entity_Id;
-               L : Elist_Id) return Boolean
-            is
-               List_Elmt : Elmt_Id;
+      --  Local variables
 
-            begin
-               List_Elmt := First_Elmt (L);
-               while Present (List_Elmt) loop
-                  if Node (List_Elmt) = E then
-                     return True;
-                  end if;
+      Full_Indic  : Node_Id;
+      Full_Parent : Entity_Id;
+      Priv_Parent : Entity_Id;
 
-                  Next_Elmt (List_Elmt);
-               end loop;
+   --  Start of processing for Process_Full_View
 
-               return False;
-            end Contains;
+   begin
+      --  First some sanity checks that must be done after semantic
+      --  decoration of the full view and thus cannot be placed with other
+      --  similar checks in Find_Type_Name
 
-         --  Start of processing
+      if not Is_Limited_Type (Priv_T)
+        and then (Is_Limited_Type (Full_T)
+                   or else Is_Limited_Composite (Full_T))
+      then
+         if In_Instance then
+            null;
+         else
+            Error_Msg_N
+              ("completion of nonlimited type cannot be limited", Full_T);
+            Explain_Limited_Type (Full_T, Full_T);
+         end if;
 
-         begin
-            if Is_Tagged_Type (Priv_T) then
-               Priv_List := Primitive_Operations (Priv_T);
-               Prim_Elmt := First_Elmt (Priv_List);
+      elsif Is_Abstract_Type (Full_T)
+        and then not Is_Abstract_Type (Priv_T)
+      then
+         Error_Msg_N
+           ("completion of nonabstract type cannot be abstract", Full_T);
 
-               --  In the case of a concurrent type completing a private tagged
-               --  type, primitives may have been declared in between the two
-               --  views. These subprograms need to be wrapped the same way
-               --  entries and protected procedures are handled because they
-               --  cannot be directly shared by the two views.
+      elsif Is_Tagged_Type (Priv_T)
+        and then Is_Limited_Type (Priv_T)
+        and then not Is_Limited_Type (Full_T)
+      then
+         --  If pragma CPP_Class was applied to the private declaration
+         --  propagate the limitedness to the full-view
 
-               if Is_Concurrent_Type (Full_T) then
-                  declare
-                     Conc_Typ  : constant Entity_Id :=
-                                   Corresponding_Record_Type (Full_T);
-                     Curr_Nod  : Node_Id := Parent (Conc_Typ);
-                     Wrap_Spec : Node_Id;
+         if Is_CPP_Class (Priv_T) then
+            Set_Is_Limited_Record (Full_T);
 
-                  begin
-                     while Present (Prim_Elmt) loop
-                        Prim := Node (Prim_Elmt);
+         --  GNAT allow its own definition of Limited_Controlled to disobey
+         --  this rule in order in ease the implementation. This test is safe
+         --  because Root_Controlled is defined in a child of System that
+         --  normal programs are not supposed to use.
 
-                        if Comes_From_Source (Prim)
-                          and then not Is_Abstract_Subprogram (Prim)
-                        then
-                           Wrap_Spec :=
-                             Make_Subprogram_Declaration (Sloc (Prim),
-                               Specification =>
-                                 Build_Wrapper_Spec
-                                   (Subp_Id => Prim,
-                                    Obj_Typ => Conc_Typ,
-                                    Formals =>
-                                      Parameter_Specifications (
-                                        Parent (Prim))));
+         elsif Is_RTE (Etype (Full_T), RE_Root_Controlled) then
+            Set_Is_Limited_Composite (Full_T);
+         else
+            Error_Msg_N
+              ("completion of limited tagged type must be limited", Full_T);
+         end if;
 
-                           Insert_After (Curr_Nod, Wrap_Spec);
-                           Curr_Nod := Wrap_Spec;
+      elsif Is_Generic_Type (Priv_T) then
+         Error_Msg_N ("generic type cannot have a completion", Full_T);
+      end if;
 
-                           Analyze (Wrap_Spec);
-                        end if;
+      --  Check that ancestor interfaces of private and full views are
+      --  consistent. We omit this check for synchronized types because
+      --  they are performed on the corresponding record type when frozen.
 
-                        Next_Elmt (Prim_Elmt);
-                     end loop;
+      if Ada_Version >= Ada_2005
+        and then Is_Tagged_Type (Priv_T)
+        and then Is_Tagged_Type (Full_T)
+        and then not Is_Concurrent_Type (Full_T)
+      then
+         declare
+            Iface         : Entity_Id;
+            Priv_T_Ifaces : constant Elist_Id := New_Elmt_List;
+            Full_T_Ifaces : constant Elist_Id := New_Elmt_List;
 
-                     return;
-                  end;
+         begin
+            Collect_Implemented_Interfaces (Priv_T, Priv_T_Ifaces);
+            Collect_Implemented_Interfaces (Full_T, Full_T_Ifaces);
 
-               --  For non-concurrent types, transfer explicit primitives, but
-               --  omit those inherited from the parent of the private view
-               --  since they will be re-inherited later on.
+            --  Ada 2005 (AI-251): The partial view shall be a descendant of
+            --  an interface type if and only if the full type is descendant
+            --  of the interface type (AARM 7.3 (7.3/2)).
 
-               else
-                  Full_List := Primitive_Operations (Full_T);
+            Iface := Find_Hidden_Interface (Priv_T_Ifaces, Full_T_Ifaces);
 
-                  while Present (Prim_Elmt) loop
-                     Prim := Node (Prim_Elmt);
+            if Present (Iface) then
+               Error_Msg_NE
+                 ("interface in partial view& not implemented by full type "
+                  & "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
+            end if;
+
+            Iface := Find_Hidden_Interface (Full_T_Ifaces, Priv_T_Ifaces);
+
+            if Present (Iface) then
+               Error_Msg_NE
+                 ("interface & not implemented by partial view "
+                  & "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
+            end if;
+         end;
+      end if;
 
-                     if Comes_From_Source (Prim)
-                       and then not Contains (Prim, Full_List)
-                     then
-                        Append_Elmt (Prim, Full_List);
-                     end if;
+      if Is_Tagged_Type (Priv_T)
+        and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
+        and then Is_Derived_Type (Full_T)
+      then
+         Priv_Parent := Etype (Priv_T);
 
-                     Next_Elmt (Prim_Elmt);
-                  end loop;
-               end if;
+         --  The full view of a private extension may have been transformed
+         --  into an unconstrained derived type declaration and a subtype
+         --  declaration (see build_derived_record_type for details).
 
-            --  Untagged private view
+         if Nkind (N) = N_Subtype_Declaration then
+            Full_Indic  := Subtype_Indication (N);
+            Full_Parent := Etype (Base_Type (Full_T));
+         else
+            Full_Indic  := Subtype_Indication (Type_Definition (N));
+            Full_Parent := Etype (Full_T);
+         end if;
 
-            else
-               Full_List := Primitive_Operations (Full_T);
+         --  Check that the parent type of the full type is a descendant of
+         --  the ancestor subtype given in the private extension. If either
+         --  entity has an Etype equal to Any_Type then we had some previous
+         --  error situation [7.3(8)].
 
-               --  In this case the partial view is untagged, so here we locate
-               --  all of the earlier primitives that need to be treated as
-               --  dispatching (those that appear between the two views). Note
-               --  that these additional operations must all be new operations
-               --  (any earlier operations that override inherited operations
-               --  of the full view will already have been inserted in the
-               --  primitives list, marked by Check_Operation_From_Private_View
-               --  as dispatching. Note that implicit "/=" operators are
-               --  excluded from being added to the primitives list since they
-               --  shouldn't be treated as dispatching (tagged "/=" is handled
-               --  specially).
+         if Priv_Parent = Any_Type or else Full_Parent = Any_Type then
+            return;
 
-               Prim := Next_Entity (Full_T);
-               while Present (Prim) and then Prim /= Priv_T loop
-                  if Ekind_In (Prim, E_Procedure, E_Function) then
-                     Disp_Typ := Find_Dispatching_Type (Prim);
+         --  Ada 2005 (AI-251): Interfaces in the full type can be given in
+         --  any order. Therefore we don't have to check that its parent must
+         --  be a descendant of the parent of the private type declaration.
 
-                     if Disp_Typ = Full_T
-                       and then (Chars (Prim) /= Name_Op_Ne
-                                  or else Comes_From_Source (Prim))
-                     then
-                        Check_Controlling_Formals (Full_T, Prim);
+         elsif Is_Interface (Priv_Parent)
+           and then Is_Interface (Full_Parent)
+         then
+            null;
 
-                        if not Is_Dispatching_Operation (Prim) then
-                           Append_Elmt (Prim, Full_List);
-                           Set_Is_Dispatching_Operation (Prim, True);
-                           Set_DT_Position (Prim, No_Uint);
-                        end if;
+         --  Ada 2005 (AI-251): If the parent of the private type declaration
+         --  is an interface there is no need to check that it is an ancestor
+         --  of the associated full type declaration. The required tests for
+         --  this case are performed by Build_Derived_Record_Type.
 
-                     elsif Is_Dispatching_Operation (Prim)
-                       and then Disp_Typ  /= Full_T
-                     then
+         elsif not Is_Interface (Base_Type (Priv_Parent))
+           and then not Is_Ancestor (Base_Type (Priv_Parent), Full_Parent)
+         then
+            Error_Msg_N
+              ("parent of full type must descend from parent"
+                  & " of private extension", Full_Indic);
 
-                        --  Verify that it is not otherwise controlled by a
-                        --  formal or a return value of type T.
+         --  First check a formal restriction, and then proceed with checking
+         --  Ada rules. Since the formal restriction is not a serious error, we
+         --  don't prevent further error detection for this check, hence the
+         --  ELSE.
 
-                        Check_Controlling_Formals (Disp_Typ, Prim);
-                     end if;
-                  end if;
+         else
+            --  In formal mode, when completing a private extension the type
+            --  named in the private part must be exactly the same as that
+            --  named in the visible part.
 
-                  Next_Entity (Prim);
-               end loop;
+            if Priv_Parent /= Full_Parent then
+               Error_Msg_Name_1 := Chars (Priv_Parent);
+               Check_SPARK_05_Restriction ("% expected", Full_Indic);
             end if;
 
-            --  For the tagged case, the two views can share the same primitive
-            --  operations list and the same class-wide type. Update attributes
-            --  of the class-wide type which depend on the full declaration.
-
-            if Is_Tagged_Type (Priv_T) then
-               Set_Direct_Primitive_Operations (Priv_T, Full_List);
-               Set_Class_Wide_Type
-                 (Base_Type (Full_T), Class_Wide_Type (Priv_T));
+            --  Check the rules of 7.3(10): if the private extension inherits
+            --  known discriminants, then the full type must also inherit those
+            --  discriminants from the same (ancestor) type, and the parent
+            --  subtype of the full type must be constrained if and only if
+            --  the ancestor subtype of the private extension is constrained.
 
-               Set_Has_Task (Class_Wide_Type (Priv_T), Has_Task      (Full_T));
-               Set_Has_Protected
-                            (Class_Wide_Type (Priv_T), Has_Protected (Full_T));
-            end if;
-         end;
-      end if;
+            if No (Discriminant_Specifications (Parent (Priv_T)))
+              and then not Has_Unknown_Discriminants (Priv_T)
+              and then Has_Discriminants (Base_Type (Priv_Parent))
+            then
+               declare
+                  Priv_Indic  : constant Node_Id :=
+                                  Subtype_Indication (Parent (Priv_T));
 
-      --  Ada 2005 AI 161: Check preelaborable initialization consistency
+                  Priv_Constr : constant Boolean :=
+                                  Is_Constrained (Priv_Parent)
+                                    or else
+                                      Nkind (Priv_Indic) = N_Subtype_Indication
+                                    or else
+                                      Is_Constrained (Entity (Priv_Indic));
 
-      if Known_To_Have_Preelab_Init (Priv_T) then
+                  Full_Constr : constant Boolean :=
+                                  Is_Constrained (Full_Parent)
+                                    or else
+                                      Nkind (Full_Indic) = N_Subtype_Indication
+                                    or else
+                                      Is_Constrained (Entity (Full_Indic));
 
-         --  Case where there is a pragma Preelaborable_Initialization. We
-         --  always allow this in predefined units, which is cheating a bit,
-         --  but it means we don't have to struggle to meet the requirements in
-         --  the RM for having Preelaborable Initialization. Otherwise we
-         --  require that the type meets the RM rules. But we can't check that
-         --  yet, because of the rule about overriding Initialize, so we simply
-         --  set a flag that will be checked at freeze time.
+                  Priv_Discr : Entity_Id;
+                  Full_Discr : Entity_Id;
 
-         if not In_Predefined_Unit (Full_T) then
-            Set_Must_Have_Preelab_Init (Full_T);
-         end if;
-      end if;
+               begin
+                  Priv_Discr := First_Discriminant (Priv_Parent);
+                  Full_Discr := First_Discriminant (Full_Parent);
+                  while Present (Priv_Discr) and then Present (Full_Discr) loop
+                     if Original_Record_Component (Priv_Discr) =
+                        Original_Record_Component (Full_Discr)
+                       or else
+                         Corresponding_Discriminant (Priv_Discr) =
+                         Corresponding_Discriminant (Full_Discr)
+                     then
+                        null;
+                     else
+                        exit;
+                     end if;
 
-      --  If pragma CPP_Class was applied to the private type declaration,
-      --  propagate it now to the full type declaration.
+                     Next_Discriminant (Priv_Discr);
+                     Next_Discriminant (Full_Discr);
+                  end loop;
 
-      if Is_CPP_Class (Priv_T) then
-         Set_Is_CPP_Class (Full_T);
-         Set_Convention   (Full_T, Convention_CPP);
+                  if Present (Priv_Discr) or else Present (Full_Discr) then
+                     Error_Msg_N
+                       ("full view must inherit discriminants of the parent"
+                        & " type used in the private extension", Full_Indic);
 
-         --  Check that components of imported CPP types do not have default
-         --  expressions.
+                  elsif Priv_Constr and then not Full_Constr then
+                     Error_Msg_N
+                       ("parent subtype of full type must be constrained",
+                        Full_Indic);
 
-         Check_CPP_Type_Has_No_Defaults (Full_T);
-      end if;
+                  elsif Full_Constr and then not Priv_Constr then
+                     Error_Msg_N
+                       ("parent subtype of full type must be unconstrained",
+                        Full_Indic);
+                  end if;
+               end;
 
-      --  If the private view has user specified stream attributes, then so has
-      --  the full view.
+               --  Check the rules of 7.3(12): if a partial view has neither
+               --  known or unknown discriminants, then the full type
+               --  declaration shall define a definite subtype.
 
-      --  Why the test, how could these flags be already set in Full_T ???
+            elsif      not Has_Unknown_Discriminants (Priv_T)
+              and then not Has_Discriminants (Priv_T)
+              and then not Is_Constrained (Full_T)
+            then
+               Error_Msg_N
+                 ("full view must define a constrained type if partial view"
+                  & " has no discriminants", Full_T);
+            end if;
 
-      if Has_Specified_Stream_Read (Priv_T) then
-         Set_Has_Specified_Stream_Read (Full_T);
-      end if;
+            --  ??????? Do we implement the following properly ?????
+            --  If the ancestor subtype of a private extension has constrained
+            --  discriminants, then the parent subtype of the full view shall
+            --  impose a statically matching constraint on those discriminants
+            --  [7.3(13)].
+         end if;
 
-      if Has_Specified_Stream_Write (Priv_T) then
-         Set_Has_Specified_Stream_Write (Full_T);
-      end if;
+      else
+         --  For untagged types, verify that a type without discriminants is
+         --  not completed with an unconstrained type. A separate error message
+         --  is produced if the full type has defaulted discriminants.
 
-      if Has_Specified_Stream_Input (Priv_T) then
-         Set_Has_Specified_Stream_Input (Full_T);
-      end if;
+         if not Is_Indefinite_Subtype (Priv_T)
+           and then Is_Indefinite_Subtype (Full_T)
+         then
+            Error_Msg_Sloc := Sloc (Parent (Priv_T));
+            Error_Msg_NE
+              ("full view of& not compatible with declaration#",
+               Full_T, Priv_T);
 
-      if Has_Specified_Stream_Output (Priv_T) then
-         Set_Has_Specified_Stream_Output (Full_T);
+            if not Is_Tagged_Type (Full_T) then
+               Error_Msg_N
+                 ("\one is constrained, the other unconstrained", Full_T);
+            end if;
+         end if;
       end if;
 
-      --  Propagate invariants to full type
+      --  AI-419: verify that the use of "limited" is consistent
 
-      if Has_Invariants (Priv_T) then
-         Set_Has_Invariants (Full_T);
-         Set_Invariant_Procedure (Full_T, Invariant_Procedure (Priv_T));
-      end if;
+      declare
+         Orig_Decl : constant Node_Id := Original_Node (N);
 
-      if Has_Inheritable_Invariants (Priv_T) then
-         Set_Has_Inheritable_Invariants (Full_T);
-      end if;
+      begin
+         if Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
+           and then Nkind (Orig_Decl) = N_Full_Type_Declaration
+           and then Nkind
+             (Type_Definition (Orig_Decl)) = N_Derived_Type_Definition
+         then
+            if not Limited_Present (Parent (Priv_T))
+              and then not Synchronized_Present (Parent (Priv_T))
+              and then Limited_Present (Type_Definition (Orig_Decl))
+            then
+               Error_Msg_N
+                 ("full view of non-limited extension cannot be limited", N);
 
-      --  Propagate predicates to full type, and predicate function if already
-      --  defined. It is not clear that this can actually happen? the partial
-      --  view cannot be frozen yet, and the predicate function has not been
-      --  built. Still it is a cheap check and seems safer to make it.
+            --  Conversely, if the partial view carries the limited keyword,
+            --  the full view must as well, even if it may be redundant.
 
-      if Has_Predicates (Priv_T) then
-         if Present (Predicate_Function (Priv_T)) then
-            Set_Predicate_Function (Full_T, Predicate_Function (Priv_T));
+            elsif Limited_Present (Parent (Priv_T))
+              and then not Limited_Present (Type_Definition (Orig_Decl))
+            then
+               Error_Msg_N
+                 ("full view of limited extension must be explicitly limited",
+                  N);
+            end if;
          end if;
+      end;
 
-         Set_Has_Predicates (Full_T);
-      end if;
-   end Process_Full_View;
-
-   -----------------------------------
-   -- Process_Incomplete_Dependents --
-   -----------------------------------
+      --  Ada 2005 (AI-443): A synchronized private extension must be
+      --  completed by a task or protected type.
 
-   procedure Process_Incomplete_Dependents
-     (N      : Node_Id;
-      Full_T : Entity_Id;
-      Inc_T  : Entity_Id)
-   is
-      Inc_Elmt : Elmt_Id;
-      Priv_Dep : Entity_Id;
-      New_Subt : Entity_Id;
+      if Ada_Version >= Ada_2005
+        and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
+        and then Synchronized_Present (Parent (Priv_T))
+        and then not Is_Concurrent_Type (Full_T)
+      then
+         Error_Msg_N ("full view of synchronized extension must " &
+                      "be synchronized type", N);
+      end if;
 
-      Disc_Constraint : Elist_Id;
+      --  Ada 2005 AI-363: if the full view has discriminants with
+      --  defaults, it is illegal to declare constrained access subtypes
+      --  whose designated type is the current type. This allows objects
+      --  of the type that are declared in the heap to be unconstrained.
 
-   begin
-      if No (Private_Dependents (Inc_T)) then
-         return;
+      if not Has_Unknown_Discriminants (Priv_T)
+        and then not Has_Discriminants (Priv_T)
+        and then Has_Discriminants (Full_T)
+        and then
+          Present (Discriminant_Default_Value (First_Discriminant (Full_T)))
+      then
+         Set_Has_Constrained_Partial_View (Full_T);
+         Set_Has_Constrained_Partial_View (Priv_T);
       end if;
 
-      --  Itypes that may be generated by the completion of an incomplete
-      --  subtype are not used by the back-end and not attached to the tree.
-      --  They are created only for constraint-checking purposes.
+      --  Create a full declaration for all its subtypes recorded in
+      --  Private_Dependents and swap them similarly to the base type. These
+      --  are subtypes that have been define before the full declaration of
+      --  the private type. We also swap the entry in Private_Dependents list
+      --  so we can properly restore the private view on exit from the scope.
 
-      Inc_Elmt := First_Elmt (Private_Dependents (Inc_T));
-      while Present (Inc_Elmt) loop
-         Priv_Dep := Node (Inc_Elmt);
+      declare
+         Priv_Elmt : Elmt_Id;
+         Priv_Scop : Entity_Id;
+         Priv      : Entity_Id;
+         Full      : Entity_Id;
 
-         if Ekind (Priv_Dep) = E_Subprogram_Type then
+      begin
+         Priv_Elmt := First_Elmt (Private_Dependents (Priv_T));
+         while Present (Priv_Elmt) loop
+            Priv := Node (Priv_Elmt);
+            Priv_Scop := Scope (Priv);
 
-            --  An Access_To_Subprogram type may have a return type or a
-            --  parameter type that is incomplete. Replace with the full view.
+            if Ekind_In (Priv, E_Private_Subtype,
+                               E_Limited_Private_Subtype,
+                               E_Record_Subtype_With_Private)
+            then
+               Full := Make_Defining_Identifier (Sloc (Priv), Chars (Priv));
+               Set_Is_Itype (Full);
+               Set_Parent (Full, Parent (Priv));
+               Set_Associated_Node_For_Itype (Full, N);
 
-            if Etype (Priv_Dep) = Inc_T then
-               Set_Etype (Priv_Dep, Full_T);
-            end if;
+               --  Now we need to complete the private subtype, but since the
+               --  base type has already been swapped, we must also swap the
+               --  subtypes (and thus, reverse the arguments in the call to
+               --  Complete_Private_Subtype). Also note that we may need to
+               --  re-establish the scope of the private subtype.
 
-            declare
-               Formal : Entity_Id;
+               Copy_And_Swap (Priv, Full);
 
-            begin
-               Formal := First_Formal (Priv_Dep);
-               while Present (Formal) loop
-                  if Etype (Formal) = Inc_T then
-                     Set_Etype (Formal, Full_T);
-                  end if;
+               if not In_Open_Scopes (Priv_Scop) then
+                  Push_Scope (Priv_Scop);
 
-                  Next_Formal (Formal);
-               end loop;
-            end;
+               else
+                  --  Reset Priv_Scop to Empty to indicate no scope was pushed
 
-         elsif Is_Overloadable (Priv_Dep) then
+                  Priv_Scop := Empty;
+               end if;
 
-            --  If a subprogram in the incomplete dependents list is primitive
-            --  for a tagged full type then mark it as a dispatching operation,
-            --  check whether it overrides an inherited subprogram, and check
-            --  restrictions on its controlling formals. Note that a protected
-            --  operation is never dispatching: only its wrapper operation
-            --  (which has convention Ada) is.
+               Complete_Private_Subtype (Full, Priv, Full_T, N);
 
-            if Is_Tagged_Type (Full_T)
-              and then Is_Primitive (Priv_Dep)
-              and then Convention (Priv_Dep) /= Convention_Protected
-            then
-               Check_Operation_From_Incomplete_Type (Priv_Dep, Inc_T);
-               Set_Is_Dispatching_Operation (Priv_Dep);
-               Check_Controlling_Formals (Full_T, Priv_Dep);
-            end if;
+               if Present (Priv_Scop) then
+                  Pop_Scope;
+               end if;
 
-         elsif Ekind (Priv_Dep) = E_Subprogram_Body then
+               Replace_Elmt (Priv_Elmt, Full);
+            end if;
 
-            --  Can happen during processing of a body before the completion
-            --  of a TA type. Ignore, because spec is also on dependent list.
+            Next_Elmt (Priv_Elmt);
+         end loop;
+      end;
 
-            return;
+      --  If the private view was tagged, copy the new primitive operations
+      --  from the private view to the full view.
 
-         --  Ada 2005 (AI-412): Transform a regular incomplete subtype into a
-         --  corresponding subtype of the full view.
+      if Is_Tagged_Type (Full_T) then
+         declare
+            Disp_Typ  : Entity_Id;
+            Full_List : Elist_Id;
+            Prim      : Entity_Id;
+            Prim_Elmt : Elmt_Id;
+            Priv_List : Elist_Id;
 
-         elsif Ekind (Priv_Dep) = E_Incomplete_Subtype then
-            Set_Subtype_Indication
-              (Parent (Priv_Dep), New_Occurrence_Of (Full_T, Sloc (Priv_Dep)));
-            Set_Etype (Priv_Dep, Full_T);
-            Set_Ekind (Priv_Dep, Subtype_Kind (Ekind (Full_T)));
-            Set_Analyzed (Parent (Priv_Dep), False);
+            function Contains
+              (E : Entity_Id;
+               L : Elist_Id) return Boolean;
+            --  Determine whether list L contains element E
 
-            --  Reanalyze the declaration, suppressing the call to
-            --  Enter_Name to avoid duplicate names.
+            --------------
+            -- Contains --
+            --------------
 
-            Analyze_Subtype_Declaration
-              (N    => Parent (Priv_Dep),
-               Skip => True);
+            function Contains
+              (E : Entity_Id;
+               L : Elist_Id) return Boolean
+            is
+               List_Elmt : Elmt_Id;
 
-         --  Dependent is a subtype
+            begin
+               List_Elmt := First_Elmt (L);
+               while Present (List_Elmt) loop
+                  if Node (List_Elmt) = E then
+                     return True;
+                  end if;
 
-         else
-            --  We build a new subtype indication using the full view of the
-            --  incomplete parent. The discriminant constraints have been
-            --  elaborated already at the point of the subtype declaration.
+                  Next_Elmt (List_Elmt);
+               end loop;
 
-            New_Subt := Create_Itype (E_Void, N);
+               return False;
+            end Contains;
 
-            if Has_Discriminants (Full_T) then
-               Disc_Constraint := Discriminant_Constraint (Priv_Dep);
-            else
-               Disc_Constraint := No_Elist;
-            end if;
+         --  Start of processing
 
-            Build_Discriminated_Subtype (Full_T, New_Subt, Disc_Constraint, N);
-            Set_Full_View (Priv_Dep, New_Subt);
-         end if;
+         begin
+            if Is_Tagged_Type (Priv_T) then
+               Priv_List := Primitive_Operations (Priv_T);
+               Prim_Elmt := First_Elmt (Priv_List);
 
-         Next_Elmt (Inc_Elmt);
-      end loop;
-   end Process_Incomplete_Dependents;
+               --  In the case of a concurrent type completing a private tagged
+               --  type, primitives may have been declared in between the two
+               --  views. These subprograms need to be wrapped the same way
+               --  entries and protected procedures are handled because they
+               --  cannot be directly shared by the two views.
 
-   --------------------------------
-   -- Process_Range_Expr_In_Decl --
-   --------------------------------
+               if Is_Concurrent_Type (Full_T) then
+                  declare
+                     Conc_Typ  : constant Entity_Id :=
+                                   Corresponding_Record_Type (Full_T);
+                     Curr_Nod  : Node_Id := Parent (Conc_Typ);
+                     Wrap_Spec : Node_Id;
 
-   procedure Process_Range_Expr_In_Decl
-     (R            : Node_Id;
-      T            : Entity_Id;
-      Subtyp       : Entity_Id := Empty;
-      Check_List   : List_Id   := Empty_List;
-      R_Check_Off  : Boolean   := False;
-      In_Iter_Schm : Boolean   := False)
-   is
-      Lo, Hi      : Node_Id;
-      R_Checks    : Check_Result;
-      Insert_Node : Node_Id;
-      Def_Id      : Entity_Id;
+                  begin
+                     while Present (Prim_Elmt) loop
+                        Prim := Node (Prim_Elmt);
 
-   begin
-      Analyze_And_Resolve (R, Base_Type (T));
+                        if Comes_From_Source (Prim)
+                          and then not Is_Abstract_Subprogram (Prim)
+                        then
+                           Wrap_Spec :=
+                             Make_Subprogram_Declaration (Sloc (Prim),
+                               Specification =>
+                                 Build_Wrapper_Spec
+                                   (Subp_Id => Prim,
+                                    Obj_Typ => Conc_Typ,
+                                    Formals =>
+                                      Parameter_Specifications (
+                                        Parent (Prim))));
 
-      if Nkind (R) = N_Range then
+                           Insert_After (Curr_Nod, Wrap_Spec);
+                           Curr_Nod := Wrap_Spec;
 
-         --  In SPARK, all ranges should be static, with the exception of the
-         --  discrete type definition of a loop parameter specification.
+                           Analyze (Wrap_Spec);
+                        end if;
 
-         if not In_Iter_Schm
-           and then not Is_OK_Static_Range (R)
-         then
-            Check_SPARK_Restriction ("range should be static", R);
-         end if;
+                        Next_Elmt (Prim_Elmt);
+                     end loop;
 
-         Lo := Low_Bound (R);
-         Hi := High_Bound (R);
+                     return;
+                  end;
 
-         --  We need to ensure validity of the bounds here, because if we
-         --  go ahead and do the expansion, then the expanded code will get
-         --  analyzed with range checks suppressed and we miss the check.
-         --  Validity checks on the range of a quantified expression are
-         --  delayed until the construct is transformed into a loop.
+               --  For non-concurrent types, transfer explicit primitives, but
+               --  omit those inherited from the parent of the private view
+               --  since they will be re-inherited later on.
 
-         if Nkind (Parent (R)) /= N_Loop_Parameter_Specification
-           or else Nkind (Parent (Parent (R))) /= N_Quantified_Expression
-         then
-            Validity_Check_Range (R);
-         end if;
+               else
+                  Full_List := Primitive_Operations (Full_T);
 
-         --  If there were errors in the declaration, try and patch up some
-         --  common mistakes in the bounds. The cases handled are literals
-         --  which are Integer where the expected type is Real and vice versa.
-         --  These corrections allow the compilation process to proceed further
-         --  along since some basic assumptions of the format of the bounds
-         --  are guaranteed.
+                  while Present (Prim_Elmt) loop
+                     Prim := Node (Prim_Elmt);
 
-         if Etype (R) = Any_Type then
-            if Nkind (Lo) = N_Integer_Literal and then Is_Real_Type (T) then
-               Rewrite (Lo,
-                 Make_Real_Literal (Sloc (Lo), UR_From_Uint (Intval (Lo))));
+                     if Comes_From_Source (Prim)
+                       and then not Contains (Prim, Full_List)
+                     then
+                        Append_Elmt (Prim, Full_List);
+                     end if;
 
-            elsif Nkind (Hi) = N_Integer_Literal and then Is_Real_Type (T) then
-               Rewrite (Hi,
-                 Make_Real_Literal (Sloc (Hi), UR_From_Uint (Intval (Hi))));
+                     Next_Elmt (Prim_Elmt);
+                  end loop;
+               end if;
 
-            elsif Nkind (Lo) = N_Real_Literal and then Is_Integer_Type (T) then
-               Rewrite (Lo,
-                 Make_Integer_Literal (Sloc (Lo), UR_To_Uint (Realval (Lo))));
+            --  Untagged private view
 
-            elsif Nkind (Hi) = N_Real_Literal and then Is_Integer_Type (T) then
-               Rewrite (Hi,
-                 Make_Integer_Literal (Sloc (Hi), UR_To_Uint (Realval (Hi))));
-            end if;
+            else
+               Full_List := Primitive_Operations (Full_T);
 
-            Set_Etype (Lo, T);
-            Set_Etype (Hi, T);
-         end if;
+               --  In this case the partial view is untagged, so here we locate
+               --  all of the earlier primitives that need to be treated as
+               --  dispatching (those that appear between the two views). Note
+               --  that these additional operations must all be new operations
+               --  (any earlier operations that override inherited operations
+               --  of the full view will already have been inserted in the
+               --  primitives list, marked by Check_Operation_From_Private_View
+               --  as dispatching. Note that implicit "/=" operators are
+               --  excluded from being added to the primitives list since they
+               --  shouldn't be treated as dispatching (tagged "/=" is handled
+               --  specially).
 
-         --  If the bounds of the range have been mistakenly given as string
-         --  literals (perhaps in place of character literals), then an error
-         --  has already been reported, but we rewrite the string literal as a
-         --  bound of the range's type to avoid blowups in later processing
-         --  that looks at static values.
+               Prim := Next_Entity (Full_T);
+               while Present (Prim) and then Prim /= Priv_T loop
+                  if Ekind_In (Prim, E_Procedure, E_Function) then
+                     Disp_Typ := Find_Dispatching_Type (Prim);
 
-         if Nkind (Lo) = N_String_Literal then
-            Rewrite (Lo,
-              Make_Attribute_Reference (Sloc (Lo),
-                Attribute_Name => Name_First,
-                Prefix => New_Occurrence_Of (T, Sloc (Lo))));
-            Analyze_And_Resolve (Lo);
-         end if;
+                     if Disp_Typ = Full_T
+                       and then (Chars (Prim) /= Name_Op_Ne
+                                  or else Comes_From_Source (Prim))
+                     then
+                        Check_Controlling_Formals (Full_T, Prim);
 
-         if Nkind (Hi) = N_String_Literal then
-            Rewrite (Hi,
-              Make_Attribute_Reference (Sloc (Hi),
-                Attribute_Name => Name_First,
-                Prefix => New_Occurrence_Of (T, Sloc (Hi))));
-            Analyze_And_Resolve (Hi);
-         end if;
+                        if not Is_Dispatching_Operation (Prim) then
+                           Append_Elmt (Prim, Full_List);
+                           Set_Is_Dispatching_Operation (Prim, True);
+                           Set_DT_Position_Value (Prim, No_Uint);
+                        end if;
 
-         --  If bounds aren't scalar at this point then exit, avoiding
-         --  problems with further processing of the range in this procedure.
+                     elsif Is_Dispatching_Operation (Prim)
+                       and then Disp_Typ  /= Full_T
+                     then
 
-         if not Is_Scalar_Type (Etype (Lo)) then
-            return;
-         end if;
+                        --  Verify that it is not otherwise controlled by a
+                        --  formal or a return value of type T.
 
-         --  Resolve (actually Sem_Eval) has checked that the bounds are in
-         --  then range of the base type. Here we check whether the bounds
-         --  are in the range of the subtype itself. Note that if the bounds
-         --  represent the null range the Constraint_Error exception should
-         --  not be raised.
+                        Check_Controlling_Formals (Disp_Typ, Prim);
+                     end if;
+                  end if;
 
-         --  ??? The following code should be cleaned up as follows
+                  Next_Entity (Prim);
+               end loop;
+            end if;
 
-         --  1. The Is_Null_Range (Lo, Hi) test should disappear since it
-         --     is done in the call to Range_Check (R, T); below
+            --  For the tagged case, the two views can share the same primitive
+            --  operations list and the same class-wide type. Update attributes
+            --  of the class-wide type which depend on the full declaration.
 
-         --  2. The use of R_Check_Off should be investigated and possibly
-         --     removed, this would clean up things a bit.
+            if Is_Tagged_Type (Priv_T) then
+               Set_Direct_Primitive_Operations (Priv_T, Full_List);
+               Set_Class_Wide_Type
+                 (Base_Type (Full_T), Class_Wide_Type (Priv_T));
 
-         if Is_Null_Range (Lo, Hi) then
-            null;
+               Set_Has_Task (Class_Wide_Type (Priv_T), Has_Task      (Full_T));
+               Set_Has_Protected
+                            (Class_Wide_Type (Priv_T), Has_Protected (Full_T));
+            end if;
+         end;
+      end if;
 
-         else
-            --  Capture values of bounds and generate temporaries for them
-            --  if needed, before applying checks, since checks may cause
-            --  duplication of the expression without forcing evaluation.
+      --  Ada 2005 AI 161: Check preelaborable initialization consistency
 
-            --  The forced evaluation removes side effects from expressions,
-            --  which should occur also in GNATprove mode. Otherwise, we end up
-            --  with unexpected insertions of actions at places where this is
-            --  not supposed to occur, e.g. on default parameters of a call.
+      if Known_To_Have_Preelab_Init (Priv_T) then
 
-            if Expander_Active or GNATprove_Mode then
+         --  Case where there is a pragma Preelaborable_Initialization. We
+         --  always allow this in predefined units, which is cheating a bit,
+         --  but it means we don't have to struggle to meet the requirements in
+         --  the RM for having Preelaborable Initialization. Otherwise we
+         --  require that the type meets the RM rules. But we can't check that
+         --  yet, because of the rule about overriding Initialize, so we simply
+         --  set a flag that will be checked at freeze time.
 
-               --  If no subtype name, then just call Force_Evaluation to
-               --  create declarations as needed to deal with side effects.
-               --  Also ignore calls from within a record type, where we
-               --  have possible scoping issues.
+         if not In_Predefined_Unit (Full_T) then
+            Set_Must_Have_Preelab_Init (Full_T);
+         end if;
+      end if;
 
-               if No (Subtyp) or else Is_Record_Type (Current_Scope) then
-                  Force_Evaluation (Lo);
-                  Force_Evaluation (Hi);
+      --  If pragma CPP_Class was applied to the private type declaration,
+      --  propagate it now to the full type declaration.
 
-               --  If a subtype is given, then we capture the bounds if they
-               --  are not known at compile time, using constant identifiers
-               --  xxx_FIRST and xxx_LAST where xxx is the name of the subtype.
+      if Is_CPP_Class (Priv_T) then
+         Set_Is_CPP_Class (Full_T);
+         Set_Convention   (Full_T, Convention_CPP);
 
-               --  Note: we do this transformation even if expansion is not
-               --  active, and in particular we do it in GNATprove_Mode since
-               --  the transformation is in general required to ensure that the
-               --  resulting tree has proper Ada semantics.
+         --  Check that components of imported CPP types do not have default
+         --  expressions.
 
-               --  Historical note: We used to just do Force_Evaluation calls
-               --  in all cases, but it is better to capture the bounds with
-               --  proper non-serialized names, since these will be accessed
-               --  from other units, and hence may be public, and also we can
-               --  then expand 'First and 'Last references to be references to
-               --  these special names.
+         Check_CPP_Type_Has_No_Defaults (Full_T);
+      end if;
 
-               else
-                  if not Compile_Time_Known_Value (Lo)
+      --  If the private view has user specified stream attributes, then so has
+      --  the full view.
 
-                    --  No need to capture bounds if they already are
-                    --  references to constants.
+      --  Why the test, how could these flags be already set in Full_T ???
 
-                    and then not (Is_Entity_Name (Lo)
-                                   and then Is_Constant_Object (Entity (Lo)))
-                  then
-                     declare
-                        Loc : constant Source_Ptr := Sloc (Lo);
-                        Lov : constant Entity_Id  :=
-                          Make_Defining_Identifier (Loc,
-                            Chars =>
-                              New_External_Name (Chars (Subtyp), "_FIRST"));
-                     begin
-                        Insert_Action (R,
-                          Make_Object_Declaration (Loc,
-                            Defining_Identifier => Lov,
-                            Object_Definition   =>
-                              New_Occurrence_Of (Base_Type (T), Loc),
-                            Constant_Present    => True,
-                            Expression          => Relocate_Node (Lo)));
-                        Rewrite (Lo, New_Occurrence_Of (Lov, Loc));
-                     end;
-                  end if;
+      if Has_Specified_Stream_Read (Priv_T) then
+         Set_Has_Specified_Stream_Read (Full_T);
+      end if;
 
-                  if not Compile_Time_Known_Value (Hi)
-                    and then not (Is_Entity_Name (Hi)
-                                  and then Is_Constant_Object (Entity (Hi)))
-                  then
-                     declare
-                        Loc : constant Source_Ptr := Sloc (Hi);
-                        Hiv : constant Entity_Id  :=
-                          Make_Defining_Identifier (Loc,
-                            Chars =>
-                              New_External_Name (Chars (Subtyp), "_LAST"));
-                     begin
-                        Insert_Action (R,
-                          Make_Object_Declaration (Loc,
-                            Defining_Identifier => Hiv,
-                            Object_Definition   =>
-                              New_Occurrence_Of (Base_Type (T), Loc),
-                            Constant_Present    => True,
-                            Expression          => Relocate_Node (Hi)));
-                        Rewrite (Hi, New_Occurrence_Of (Hiv, Loc));
-                     end;
-                  end if;
-               end if;
-            end if;
+      if Has_Specified_Stream_Write (Priv_T) then
+         Set_Has_Specified_Stream_Write (Full_T);
+      end if;
 
-            --  We use a flag here instead of suppressing checks on the
-            --  type because the type we check against isn't necessarily
-            --  the place where we put the check.
+      if Has_Specified_Stream_Input (Priv_T) then
+         Set_Has_Specified_Stream_Input (Full_T);
+      end if;
 
-            if not R_Check_Off then
-               R_Checks := Get_Range_Checks (R, T);
+      if Has_Specified_Stream_Output (Priv_T) then
+         Set_Has_Specified_Stream_Output (Full_T);
+      end if;
 
-               --  Look up tree to find an appropriate insertion point. We
-               --  can't just use insert_actions because later processing
-               --  depends on the insertion node. Prior to Ada 2012 the
-               --  insertion point could only be a declaration or a loop, but
-               --  quantified expressions can appear within any context in an
-               --  expression, and the insertion point can be any statement,
-               --  pragma, or declaration.
+      --  Propagate the attributes related to pragma Default_Initial_Condition
+      --  from the private to the full view. Note that both flags are mutually
+      --  exclusive.
 
-               Insert_Node := Parent (R);
-               while Present (Insert_Node) loop
-                  exit when
-                    Nkind (Insert_Node) in N_Declaration
-                    and then
-                      not Nkind_In
-                        (Insert_Node, N_Component_Declaration,
-                                      N_Loop_Parameter_Specification,
-                                      N_Function_Specification,
-                                      N_Procedure_Specification);
+      if Has_Default_Init_Cond (Priv_T)
+        or else Has_Inherited_Default_Init_Cond (Priv_T)
+      then
+         Propagate_Default_Init_Cond_Attributes
+           (From_Typ             => Priv_T,
+            To_Typ               => Full_T,
+            Private_To_Full_View => True);
+
+      --  In the case where the full view is derived from another private type,
+      --  the attributes related to pragma Default_Initial_Condition must be
+      --  propagated from the full to the private view to maintain consistency
+      --  of views.
+
+      --    package Pack is
+      --       type Parent_Typ is private
+      --         with Default_Initial_Condition ...;
+      --    private
+      --       type Parent_Typ is ...;
+      --    end Pack;
+
+      --    with Pack; use Pack;
+      --    package Pack_2 is
+      --       type Deriv_Typ is private;         --  must inherit
+      --    private
+      --       type Deriv_Typ is new Parent_Typ;  --  must inherit
+      --    end Pack_2;
+
+      elsif Has_Default_Init_Cond (Full_T)
+        or else Has_Inherited_Default_Init_Cond (Full_T)
+      then
+         Propagate_Default_Init_Cond_Attributes
+           (From_Typ             => Full_T,
+            To_Typ               => Priv_T,
+            Private_To_Full_View => True);
+      end if;
 
-                  exit when Nkind (Insert_Node) in N_Later_Decl_Item
-                    or else Nkind (Insert_Node) in
-                              N_Statement_Other_Than_Procedure_Call
-                    or else Nkind_In (Insert_Node, N_Procedure_Call_Statement,
-                                                   N_Pragma);
+      --  Propagate the attributes related to pragma Ghost from the private to
+      --  the full view.
 
-                  Insert_Node := Parent (Insert_Node);
-               end loop;
+      if Is_Ghost_Entity (Priv_T) then
+         Set_Is_Ghost_Entity (Full_T);
 
-               --  Why would Type_Decl not be present???  Without this test,
-               --  short regression tests fail.
+         --  The Ghost policy in effect at the point of declaration and at the
+         --  point of completion must match (SPARK RM 6.9(14)).
 
-               if Present (Insert_Node) then
+         Check_Ghost_Completion (Priv_T, Full_T);
 
-                  --  Case of loop statement. Verify that the range is part
-                  --  of the subtype indication of the iteration scheme.
+         --  In the case where the private view of a tagged type lacks a parent
+         --  type and is subject to pragma Ghost, ensure that the parent type
+         --  specified by the full view is also Ghost (SPARK RM 6.9(9)).
 
-                  if Nkind (Insert_Node) = N_Loop_Statement then
-                     declare
-                        Indic : Node_Id;
+         if Is_Derived_Type (Full_T) then
+            Check_Ghost_Derivation (Full_T);
+         end if;
+      end if;
 
-                     begin
-                        Indic := Parent (R);
-                        while Present (Indic)
-                          and then Nkind (Indic) /= N_Subtype_Indication
-                        loop
-                           Indic := Parent (Indic);
-                        end loop;
+      --  Propagate invariants to full type
 
-                        if Present (Indic) then
-                           Def_Id := Etype (Subtype_Mark (Indic));
+      if Has_Invariants (Priv_T) then
+         Set_Has_Invariants (Full_T);
+         Set_Invariant_Procedure (Full_T, Invariant_Procedure (Priv_T));
+      end if;
 
-                           Insert_Range_Checks
-                             (R_Checks,
-                              Insert_Node,
-                              Def_Id,
-                              Sloc (Insert_Node),
-                              R,
-                              Do_Before => True);
-                        end if;
-                     end;
+      if Has_Inheritable_Invariants (Priv_T) then
+         Set_Has_Inheritable_Invariants (Full_T);
+      end if;
 
-                  --  Insertion before a declaration. If the declaration
-                  --  includes discriminants, the list of applicable checks
-                  --  is given by the caller.
+      --  Check hidden inheritance of class-wide type invariants
 
-                  elsif Nkind (Insert_Node) in N_Declaration then
-                     Def_Id := Defining_Identifier (Insert_Node);
+      if Ada_Version >= Ada_2012
+        and then not Has_Inheritable_Invariants (Full_T)
+        and then In_Private_Part (Current_Scope)
+        and then Has_Interfaces (Full_T)
+      then
+         declare
+            Ifaces : Elist_Id;
+            AI     : Elmt_Id;
 
-                     if (Ekind (Def_Id) = E_Record_Type
-                          and then Depends_On_Discriminant (R))
-                       or else
-                        (Ekind (Def_Id) = E_Protected_Type
-                          and then Has_Discriminants (Def_Id))
-                     then
-                        Append_Range_Checks
-                          (R_Checks,
-                            Check_List, Def_Id, Sloc (Insert_Node), R);
+         begin
+            Collect_Interfaces (Full_T, Ifaces, Exclude_Parents => True);
 
-                     else
-                        Insert_Range_Checks
-                          (R_Checks,
-                            Insert_Node, Def_Id, Sloc (Insert_Node), R);
+            AI := First_Elmt (Ifaces);
+            while Present (AI) loop
+               if Has_Inheritable_Invariants (Node (AI)) then
+                  Error_Msg_N
+                    ("hidden inheritance of class-wide type invariants " &
+                     "not allowed", N);
+                  exit;
+               end if;
 
-                     end if;
+               Next_Elmt (AI);
+            end loop;
+         end;
+      end if;
 
-                  --  Insertion before a statement. Range appears in the
-                  --  context of a quantified expression. Insertion will
-                  --  take place when expression is expanded.
+      --  Propagate predicates to full type, and predicate function if already
+      --  defined. It is not clear that this can actually happen? the partial
+      --  view cannot be frozen yet, and the predicate function has not been
+      --  built. Still it is a cheap check and seems safer to make it.
 
-                  else
-                     null;
-                  end if;
-               end if;
-            end if;
+      if Has_Predicates (Priv_T) then
+         if Present (Predicate_Function (Priv_T)) then
+            Set_Predicate_Function (Full_T, Predicate_Function (Priv_T));
          end if;
 
-      --  Case of other than an explicit N_Range node
+         Set_Has_Predicates (Full_T);
+      end if;
+   end Process_Full_View;
 
-      --  The forced evaluation removes side effects from expressions, which
-      --  should occur also in GNATprove mode. Otherwise, we end up with
-      --  unexpected insertions of actions at places where this is not
-      --  supposed to occur, e.g. on default parameters of a call.
+   -----------------------------------
+   -- Process_Incomplete_Dependents --
+   -----------------------------------
 
-      elsif Expander_Active or GNATprove_Mode then
-         Get_Index_Bounds (R, Lo, Hi);
-         Force_Evaluation (Lo);
-         Force_Evaluation (Hi);
+   procedure Process_Incomplete_Dependents
+     (N      : Node_Id;
+      Full_T : Entity_Id;
+      Inc_T  : Entity_Id)
+   is
+      Inc_Elmt : Elmt_Id;
+      Priv_Dep : Entity_Id;
+      New_Subt : Entity_Id;
+
+      Disc_Constraint : Elist_Id;
+
+   begin
+      if No (Private_Dependents (Inc_T)) then
+         return;
       end if;
-   end Process_Range_Expr_In_Decl;
 
-   --------------------------------------
-   -- Process_Real_Range_Specification --
-   --------------------------------------
+      --  Itypes that may be generated by the completion of an incomplete
+      --  subtype are not used by the back-end and not attached to the tree.
+      --  They are created only for constraint-checking purposes.
 
-   procedure Process_Real_Range_Specification (Def : Node_Id) is
-      Spec : constant Node_Id := Real_Range_Specification (Def);
-      Lo   : Node_Id;
-      Hi   : Node_Id;
-      Err  : Boolean := False;
+      Inc_Elmt := First_Elmt (Private_Dependents (Inc_T));
+      while Present (Inc_Elmt) loop
+         Priv_Dep := Node (Inc_Elmt);
 
-      procedure Analyze_Bound (N : Node_Id);
-      --  Analyze and check one bound
+         if Ekind (Priv_Dep) = E_Subprogram_Type then
 
-      -------------------
-      -- Analyze_Bound --
-      -------------------
+            --  An Access_To_Subprogram type may have a return type or a
+            --  parameter type that is incomplete. Replace with the full view.
 
-      procedure Analyze_Bound (N : Node_Id) is
-      begin
-         Analyze_And_Resolve (N, Any_Real);
+            if Etype (Priv_Dep) = Inc_T then
+               Set_Etype (Priv_Dep, Full_T);
+            end if;
 
-         if not Is_OK_Static_Expression (N) then
-            Flag_Non_Static_Expr
-              ("bound in real type definition is not static!", N);
-            Err := True;
-         end if;
-      end Analyze_Bound;
+            declare
+               Formal : Entity_Id;
 
-   --  Start of processing for Process_Real_Range_Specification
+            begin
+               Formal := First_Formal (Priv_Dep);
+               while Present (Formal) loop
+                  if Etype (Formal) = Inc_T then
+                     Set_Etype (Formal, Full_T);
+                  end if;
 
-   begin
-      if Present (Spec) then
-         Lo := Low_Bound (Spec);
-         Hi := High_Bound (Spec);
-         Analyze_Bound (Lo);
-         Analyze_Bound (Hi);
+                  Next_Formal (Formal);
+               end loop;
+            end;
 
-         --  If error, clear away junk range specification
+         elsif Is_Overloadable (Priv_Dep) then
 
-         if Err then
-            Set_Real_Range_Specification (Def, Empty);
-         end if;
-      end if;
-   end Process_Real_Range_Specification;
+            --  If a subprogram in the incomplete dependents list is primitive
+            --  for a tagged full type then mark it as a dispatching operation,
+            --  check whether it overrides an inherited subprogram, and check
+            --  restrictions on its controlling formals. Note that a protected
+            --  operation is never dispatching: only its wrapper operation
+            --  (which has convention Ada) is.
 
-   ---------------------
-   -- Process_Subtype --
-   ---------------------
+            if Is_Tagged_Type (Full_T)
+              and then Is_Primitive (Priv_Dep)
+              and then Convention (Priv_Dep) /= Convention_Protected
+            then
+               Check_Operation_From_Incomplete_Type (Priv_Dep, Inc_T);
+               Set_Is_Dispatching_Operation (Priv_Dep);
+               Check_Controlling_Formals (Full_T, Priv_Dep);
+            end if;
 
-   function Process_Subtype
-     (S           : Node_Id;
-      Related_Nod : Node_Id;
-      Related_Id  : Entity_Id := Empty;
-      Suffix      : Character := ' ') return Entity_Id
-   is
-      P               : Node_Id;
-      Def_Id          : Entity_Id;
-      Error_Node      : Node_Id;
-      Full_View_Id    : Entity_Id;
-      Subtype_Mark_Id : Entity_Id;
+         elsif Ekind (Priv_Dep) = E_Subprogram_Body then
 
-      May_Have_Null_Exclusion : Boolean;
+            --  Can happen during processing of a body before the completion
+            --  of a TA type. Ignore, because spec is also on dependent list.
 
-      procedure Check_Incomplete (T : Entity_Id);
-      --  Called to verify that an incomplete type is not used prematurely
+            return;
 
-      ----------------------
-      -- Check_Incomplete --
-      ----------------------
+         --  Ada 2005 (AI-412): Transform a regular incomplete subtype into a
+         --  corresponding subtype of the full view.
 
-      procedure Check_Incomplete (T : Entity_Id) is
-      begin
-         --  Ada 2005 (AI-412): Incomplete subtypes are legal
+         elsif Ekind (Priv_Dep) = E_Incomplete_Subtype then
+            Set_Subtype_Indication
+              (Parent (Priv_Dep), New_Occurrence_Of (Full_T, Sloc (Priv_Dep)));
+            Set_Etype (Priv_Dep, Full_T);
+            Set_Ekind (Priv_Dep, Subtype_Kind (Ekind (Full_T)));
+            Set_Analyzed (Parent (Priv_Dep), False);
 
-         if Ekind (Root_Type (Entity (T))) = E_Incomplete_Type
-           and then
-             not (Ada_Version >= Ada_2005
-                    and then
-                       (Nkind (Parent (T)) = N_Subtype_Declaration
-                          or else
-                            (Nkind (Parent (T)) = N_Subtype_Indication
-                               and then Nkind (Parent (Parent (T))) =
-                                          N_Subtype_Declaration)))
-         then
-            Error_Msg_N ("invalid use of type before its full declaration", T);
-         end if;
-      end Check_Incomplete;
+            --  Reanalyze the declaration, suppressing the call to
+            --  Enter_Name to avoid duplicate names.
 
-   --  Start of processing for Process_Subtype
+            Analyze_Subtype_Declaration
+              (N    => Parent (Priv_Dep),
+               Skip => True);
 
-   begin
-      --  Case of no constraints present
+         --  Dependent is a subtype
 
-      if Nkind (S) /= N_Subtype_Indication then
-         Find_Type (S);
-         Check_Incomplete (S);
-         P := Parent (S);
+         else
+            --  We build a new subtype indication using the full view of the
+            --  incomplete parent. The discriminant constraints have been
+            --  elaborated already at the point of the subtype declaration.
 
-         --  Ada 2005 (AI-231): Static check
+            New_Subt := Create_Itype (E_Void, N);
 
-         if Ada_Version >= Ada_2005
-           and then Present (P)
-           and then Null_Exclusion_Present (P)
-           and then Nkind (P) /= N_Access_To_Object_Definition
-           and then not Is_Access_Type (Entity (S))
-         then
-            Error_Msg_N ("`NOT NULL` only allowed for an access type", S);
+            if Has_Discriminants (Full_T) then
+               Disc_Constraint := Discriminant_Constraint (Priv_Dep);
+            else
+               Disc_Constraint := No_Elist;
+            end if;
+
+            Build_Discriminated_Subtype (Full_T, New_Subt, Disc_Constraint, N);
+            Set_Full_View (Priv_Dep, New_Subt);
          end if;
 
-         --  The following is ugly, can't we have a range or even a flag???
+         Next_Elmt (Inc_Elmt);
+      end loop;
+   end Process_Incomplete_Dependents;
 
-         May_Have_Null_Exclusion :=
-           Nkind_In (P, N_Access_Definition,
-                        N_Access_Function_Definition,
-                        N_Access_Procedure_Definition,
-                        N_Access_To_Object_Definition,
-                        N_Allocator,
-                        N_Component_Definition)
-             or else
-           Nkind_In (P, N_Derived_Type_Definition,
-                        N_Discriminant_Specification,
-                        N_Formal_Object_Declaration,
-                        N_Object_Declaration,
-                        N_Object_Renaming_Declaration,
-                        N_Parameter_Specification,
-                        N_Subtype_Declaration);
+   --------------------------------
+   -- Process_Range_Expr_In_Decl --
+   --------------------------------
 
-         --  Create an Itype that is a duplicate of Entity (S) but with the
-         --  null-exclusion attribute.
+   procedure Process_Range_Expr_In_Decl
+     (R            : Node_Id;
+      T            : Entity_Id;
+      Subtyp       : Entity_Id := Empty;
+      Check_List   : List_Id   := Empty_List;
+      R_Check_Off  : Boolean   := False;
+      In_Iter_Schm : Boolean   := False)
+   is
+      Lo, Hi      : Node_Id;
+      R_Checks    : Check_Result;
+      Insert_Node : Node_Id;
+      Def_Id      : Entity_Id;
 
-         if May_Have_Null_Exclusion
-           and then Is_Access_Type (Entity (S))
-           and then Null_Exclusion_Present (P)
+   begin
+      Analyze_And_Resolve (R, Base_Type (T));
 
-            --  No need to check the case of an access to object definition.
-            --  It is correct to define double not-null pointers.
+      if Nkind (R) = N_Range then
 
-            --  Example:
-            --     type Not_Null_Int_Ptr is not null access Integer;
-            --     type Acc is not null access Not_Null_Int_Ptr;
+         --  In SPARK, all ranges should be static, with the exception of the
+         --  discrete type definition of a loop parameter specification.
 
-           and then Nkind (P) /= N_Access_To_Object_Definition
+         if not In_Iter_Schm
+           and then not Is_OK_Static_Range (R)
          then
-            if Can_Never_Be_Null (Entity (S)) then
-               case Nkind (Related_Nod) is
-                  when N_Full_Type_Declaration =>
-                     if Nkind (Type_Definition (Related_Nod))
-                       in N_Array_Type_Definition
-                     then
-                        Error_Node :=
-                          Subtype_Indication
-                            (Component_Definition
-                             (Type_Definition (Related_Nod)));
-                     else
-                        Error_Node :=
-                          Subtype_Indication (Type_Definition (Related_Nod));
-                     end if;
-
-                  when N_Subtype_Declaration =>
-                     Error_Node := Subtype_Indication (Related_Nod);
+            Check_SPARK_05_Restriction ("range should be static", R);
+         end if;
 
-                  when N_Object_Declaration =>
-                     Error_Node := Object_Definition (Related_Nod);
+         Lo := Low_Bound (R);
+         Hi := High_Bound (R);
 
-                  when N_Component_Declaration =>
-                     Error_Node :=
-                       Subtype_Indication (Component_Definition (Related_Nod));
+         --  Validity checks on the range of a quantified expression are
+         --  delayed until the construct is transformed into a loop.
 
-                  when N_Allocator =>
-                     Error_Node := Expression (Related_Nod);
+         if Nkind (Parent (R)) = N_Loop_Parameter_Specification
+           and then Nkind (Parent (Parent (R))) = N_Quantified_Expression
+         then
+            null;
 
-                  when others =>
-                     pragma Assert (False);
-                     Error_Node := Related_Nod;
-               end case;
+         --  We need to ensure validity of the bounds here, because if we
+         --  go ahead and do the expansion, then the expanded code will get
+         --  analyzed with range checks suppressed and we miss the check.
 
-               Error_Msg_NE
-                 ("`NOT NULL` not allowed (& already excludes null)",
-                  Error_Node,
-                  Entity (S));
-            end if;
+         --  WARNING: The capture of the range bounds with xxx_FIRST/_LAST and
+         --  the temporaries generated by routine Remove_Side_Effects by means
+         --  of validity checks must use the same names. When a range appears
+         --  in the parent of a generic, the range is processed with checks
+         --  disabled as part of the generic context and with checks enabled
+         --  for code generation purposes. This leads to link issues as the
+         --  generic contains references to xxx_FIRST/_LAST, but the inlined
+         --  template sees the temporaries generated by Remove_Side_Effects.
 
-            Set_Etype  (S,
-              Create_Null_Excluding_Itype
-                (T           => Entity (S),
-                 Related_Nod => P));
-            Set_Entity (S, Etype (S));
+         else
+            Validity_Check_Range (R, Subtyp);
          end if;
 
-         return Entity (S);
+         --  If there were errors in the declaration, try and patch up some
+         --  common mistakes in the bounds. The cases handled are literals
+         --  which are Integer where the expected type is Real and vice versa.
+         --  These corrections allow the compilation process to proceed further
+         --  along since some basic assumptions of the format of the bounds
+         --  are guaranteed.
 
-      --  Case of constraint present, so that we have an N_Subtype_Indication
-      --  node (this node is created only if constraints are present).
+         if Etype (R) = Any_Type then
+            if Nkind (Lo) = N_Integer_Literal and then Is_Real_Type (T) then
+               Rewrite (Lo,
+                 Make_Real_Literal (Sloc (Lo), UR_From_Uint (Intval (Lo))));
 
-      else
-         Find_Type (Subtype_Mark (S));
+            elsif Nkind (Hi) = N_Integer_Literal and then Is_Real_Type (T) then
+               Rewrite (Hi,
+                 Make_Real_Literal (Sloc (Hi), UR_From_Uint (Intval (Hi))));
 
-         if Nkind (Parent (S)) /= N_Access_To_Object_Definition
-           and then not
-            (Nkind (Parent (S)) = N_Subtype_Declaration
-              and then Is_Itype (Defining_Identifier (Parent (S))))
-         then
-            Check_Incomplete (Subtype_Mark (S));
+            elsif Nkind (Lo) = N_Real_Literal and then Is_Integer_Type (T) then
+               Rewrite (Lo,
+                 Make_Integer_Literal (Sloc (Lo), UR_To_Uint (Realval (Lo))));
+
+            elsif Nkind (Hi) = N_Real_Literal and then Is_Integer_Type (T) then
+               Rewrite (Hi,
+                 Make_Integer_Literal (Sloc (Hi), UR_To_Uint (Realval (Hi))));
+            end if;
+
+            Set_Etype (Lo, T);
+            Set_Etype (Hi, T);
          end if;
 
-         P := Parent (S);
-         Subtype_Mark_Id := Entity (Subtype_Mark (S));
+         --  If the bounds of the range have been mistakenly given as string
+         --  literals (perhaps in place of character literals), then an error
+         --  has already been reported, but we rewrite the string literal as a
+         --  bound of the range's type to avoid blowups in later processing
+         --  that looks at static values.
 
-         --  Explicit subtype declaration case
+         if Nkind (Lo) = N_String_Literal then
+            Rewrite (Lo,
+              Make_Attribute_Reference (Sloc (Lo),
+                Prefix         => New_Occurrence_Of (T, Sloc (Lo)),
+                Attribute_Name => Name_First));
+            Analyze_And_Resolve (Lo);
+         end if;
 
-         if Nkind (P) = N_Subtype_Declaration then
-            Def_Id := Defining_Identifier (P);
+         if Nkind (Hi) = N_String_Literal then
+            Rewrite (Hi,
+              Make_Attribute_Reference (Sloc (Hi),
+                Prefix         => New_Occurrence_Of (T, Sloc (Hi)),
+                Attribute_Name => Name_First));
+            Analyze_And_Resolve (Hi);
+         end if;
 
-         --  Explicit derived type definition case
+         --  If bounds aren't scalar at this point then exit, avoiding
+         --  problems with further processing of the range in this procedure.
 
-         elsif Nkind (P) = N_Derived_Type_Definition then
-            Def_Id := Defining_Identifier (Parent (P));
+         if not Is_Scalar_Type (Etype (Lo)) then
+            return;
+         end if;
 
-         --  Implicit case, the Def_Id must be created as an implicit type.
-         --  The one exception arises in the case of concurrent types, array
-         --  and access types, where other subsidiary implicit types may be
-         --  created and must appear before the main implicit type. In these
-         --  cases we leave Def_Id set to Empty as a signal that Create_Itype
-         --  has not yet been called to create Def_Id.
+         --  Resolve (actually Sem_Eval) has checked that the bounds are in
+         --  then range of the base type. Here we check whether the bounds
+         --  are in the range of the subtype itself. Note that if the bounds
+         --  represent the null range the Constraint_Error exception should
+         --  not be raised.
 
-         else
-            if Is_Array_Type (Subtype_Mark_Id)
-              or else Is_Concurrent_Type (Subtype_Mark_Id)
-              or else Is_Access_Type (Subtype_Mark_Id)
-            then
-               Def_Id := Empty;
+         --  ??? The following code should be cleaned up as follows
 
-            --  For the other cases, we create a new unattached Itype,
-            --  and set the indication to ensure it gets attached later.
+         --  1. The Is_Null_Range (Lo, Hi) test should disappear since it
+         --     is done in the call to Range_Check (R, T); below
 
-            else
-               Def_Id :=
-                 Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
-            end if;
-         end if;
+         --  2. The use of R_Check_Off should be investigated and possibly
+         --     removed, this would clean up things a bit.
 
-         --  If the kind of constraint is invalid for this kind of type,
-         --  then give an error, and then pretend no constraint was given.
+         if Is_Null_Range (Lo, Hi) then
+            null;
 
-         if not Is_Valid_Constraint_Kind
-                   (Ekind (Subtype_Mark_Id), Nkind (Constraint (S)))
-         then
-            Error_Msg_N
-              ("incorrect constraint for this kind of type", Constraint (S));
+         else
+            --  Capture values of bounds and generate temporaries for them
+            --  if needed, before applying checks, since checks may cause
+            --  duplication of the expression without forcing evaluation.
 
-            Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
+            --  The forced evaluation removes side effects from expressions,
+            --  which should occur also in GNATprove mode. Otherwise, we end up
+            --  with unexpected insertions of actions at places where this is
+            --  not supposed to occur, e.g. on default parameters of a call.
 
-            --  Set Ekind of orphan itype, to prevent cascaded errors
+            if Expander_Active or GNATprove_Mode then
 
-            if Present (Def_Id) then
-               Set_Ekind (Def_Id, Ekind (Any_Type));
-            end if;
+               --  Call Force_Evaluation to create declarations as needed to
+               --  deal with side effects, and also create typ_FIRST/LAST
+               --  entities for bounds if we have a subtype name.
 
-            --  Make recursive call, having got rid of the bogus constraint
+               --  Note: we do this transformation even if expansion is not
+               --  active if we are in GNATprove_Mode since the transformation
+               --  is in general required to ensure that the resulting tree has
+               --  proper Ada semantics.
+
+               Force_Evaluation
+                 (Lo, Related_Id => Subtyp, Is_Low_Bound  => True);
+               Force_Evaluation
+                 (Hi, Related_Id => Subtyp, Is_High_Bound => True);
+            end if;
 
-            return Process_Subtype (S, Related_Nod, Related_Id, Suffix);
-         end if;
+            --  We use a flag here instead of suppressing checks on the type
+            --  because the type we check against isn't necessarily the place
+            --  where we put the check.
 
-         --  Remaining processing depends on type. Select on Base_Type kind to
-         --  ensure getting to the concrete type kind in the case of a private
-         --  subtype (needed when only doing semantic analysis).
+            if not R_Check_Off then
+               R_Checks := Get_Range_Checks (R, T);
 
-         case Ekind (Base_Type (Subtype_Mark_Id)) is
-            when Access_Kind =>
+               --  Look up tree to find an appropriate insertion point. We
+               --  can't just use insert_actions because later processing
+               --  depends on the insertion node. Prior to Ada 2012 the
+               --  insertion point could only be a declaration or a loop, but
+               --  quantified expressions can appear within any context in an
+               --  expression, and the insertion point can be any statement,
+               --  pragma, or declaration.
 
-               --  If this is a constraint on a class-wide type, discard it.
-               --  There is currently no way to express a partial discriminant
-               --  constraint on a type with unknown discriminants. This is
-               --  a pathology that the ACATS wisely decides not to test.
+               Insert_Node := Parent (R);
+               while Present (Insert_Node) loop
+                  exit when
+                    Nkind (Insert_Node) in N_Declaration
+                    and then
+                      not Nkind_In
+                        (Insert_Node, N_Component_Declaration,
+                                      N_Loop_Parameter_Specification,
+                                      N_Function_Specification,
+                                      N_Procedure_Specification);
 
-               if Is_Class_Wide_Type (Designated_Type (Subtype_Mark_Id)) then
-                  if Comes_From_Source (S) then
-                     Error_Msg_N
-                       ("constraint on class-wide type ignored??",
-                        Constraint (S));
-                  end if;
+                  exit when Nkind (Insert_Node) in N_Later_Decl_Item
+                    or else Nkind (Insert_Node) in
+                              N_Statement_Other_Than_Procedure_Call
+                    or else Nkind_In (Insert_Node, N_Procedure_Call_Statement,
+                                                   N_Pragma);
 
-                  if Nkind (P) = N_Subtype_Declaration then
-                     Set_Subtype_Indication (P,
-                        New_Occurrence_Of (Subtype_Mark_Id, Sloc (S)));
-                  end if;
+                  Insert_Node := Parent (Insert_Node);
+               end loop;
 
-                  return Subtype_Mark_Id;
-               end if;
+               --  Why would Type_Decl not be present???  Without this test,
+               --  short regression tests fail.
 
-               Constrain_Access (Def_Id, S, Related_Nod);
+               if Present (Insert_Node) then
 
-               if Expander_Active
-                 and then  Is_Itype (Designated_Type (Def_Id))
-                 and then Nkind (Related_Nod) = N_Subtype_Declaration
-                 and then not Is_Incomplete_Type (Designated_Type (Def_Id))
-               then
-                  Build_Itype_Reference
-                    (Designated_Type (Def_Id), Related_Nod);
-               end if;
+                  --  Case of loop statement. Verify that the range is part
+                  --  of the subtype indication of the iteration scheme.
 
-            when Array_Kind =>
-               Constrain_Array (Def_Id, S, Related_Nod, Related_Id, Suffix);
+                  if Nkind (Insert_Node) = N_Loop_Statement then
+                     declare
+                        Indic : Node_Id;
 
-            when Decimal_Fixed_Point_Kind =>
-               Constrain_Decimal (Def_Id, S);
+                     begin
+                        Indic := Parent (R);
+                        while Present (Indic)
+                          and then Nkind (Indic) /= N_Subtype_Indication
+                        loop
+                           Indic := Parent (Indic);
+                        end loop;
 
-            when Enumeration_Kind =>
-               Constrain_Enumeration (Def_Id, S);
-               Inherit_Predicate_Flags (Def_Id, Subtype_Mark_Id);
+                        if Present (Indic) then
+                           Def_Id := Etype (Subtype_Mark (Indic));
 
-            when Ordinary_Fixed_Point_Kind =>
-               Constrain_Ordinary_Fixed (Def_Id, S);
+                           Insert_Range_Checks
+                             (R_Checks,
+                              Insert_Node,
+                              Def_Id,
+                              Sloc (Insert_Node),
+                              R,
+                              Do_Before => True);
+                        end if;
+                     end;
 
-            when Float_Kind =>
-               Constrain_Float (Def_Id, S);
+                  --  Insertion before a declaration. If the declaration
+                  --  includes discriminants, the list of applicable checks
+                  --  is given by the caller.
 
-            when Integer_Kind =>
-               Constrain_Integer (Def_Id, S);
-               Inherit_Predicate_Flags (Def_Id, Subtype_Mark_Id);
+                  elsif Nkind (Insert_Node) in N_Declaration then
+                     Def_Id := Defining_Identifier (Insert_Node);
 
-            when E_Record_Type     |
-                 E_Record_Subtype  |
-                 Class_Wide_Kind   |
-                 E_Incomplete_Type =>
-               Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
+                     if (Ekind (Def_Id) = E_Record_Type
+                          and then Depends_On_Discriminant (R))
+                       or else
+                        (Ekind (Def_Id) = E_Protected_Type
+                          and then Has_Discriminants (Def_Id))
+                     then
+                        Append_Range_Checks
+                          (R_Checks,
+                            Check_List, Def_Id, Sloc (Insert_Node), R);
 
-               if Ekind (Def_Id) = E_Incomplete_Type then
-                  Set_Private_Dependents (Def_Id, New_Elmt_List);
-               end if;
+                     else
+                        Insert_Range_Checks
+                          (R_Checks,
+                            Insert_Node, Def_Id, Sloc (Insert_Node), R);
 
-            when Private_Kind =>
-               Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
-               Set_Private_Dependents (Def_Id, New_Elmt_List);
+                     end if;
 
-               --  In case of an invalid constraint prevent further processing
-               --  since the type constructed is missing expected fields.
+                  --  Insertion before a statement. Range appears in the
+                  --  context of a quantified expression. Insertion will
+                  --  take place when expression is expanded.
 
-               if Etype (Def_Id) = Any_Type then
-                  return Def_Id;
+                  else
+                     null;
+                  end if;
                end if;
+            end if;
+         end if;
 
-               --  If the full view is that of a task with discriminants,
-               --  we must constrain both the concurrent type and its
-               --  corresponding record type. Otherwise we will just propagate
-               --  the constraint to the full view, if available.
+      --  Case of other than an explicit N_Range node
 
-               if Present (Full_View (Subtype_Mark_Id))
-                 and then Has_Discriminants (Subtype_Mark_Id)
-                 and then Is_Concurrent_Type (Full_View (Subtype_Mark_Id))
-               then
-                  Full_View_Id :=
-                    Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
+      --  The forced evaluation removes side effects from expressions, which
+      --  should occur also in GNATprove mode. Otherwise, we end up with
+      --  unexpected insertions of actions at places where this is not
+      --  supposed to occur, e.g. on default parameters of a call.
 
-                  Set_Entity (Subtype_Mark (S), Full_View (Subtype_Mark_Id));
-                  Constrain_Concurrent (Full_View_Id, S,
-                    Related_Nod, Related_Id, Suffix);
-                  Set_Entity (Subtype_Mark (S), Subtype_Mark_Id);
-                  Set_Full_View (Def_Id, Full_View_Id);
+      elsif Expander_Active or GNATprove_Mode then
+         Get_Index_Bounds (R, Lo, Hi);
+         Force_Evaluation (Lo);
+         Force_Evaluation (Hi);
+      end if;
+   end Process_Range_Expr_In_Decl;
 
-                  --  Introduce an explicit reference to the private subtype,
-                  --  to prevent scope anomalies in gigi if first use appears
-                  --  in a nested context, e.g. a later function body.
-                  --  Should this be generated in other contexts than a full
-                  --  type declaration?
+   --------------------------------------
+   -- Process_Real_Range_Specification --
+   --------------------------------------
 
-                  if Is_Itype (Def_Id)
-                    and then
-                      Nkind (Parent (P)) = N_Full_Type_Declaration
-                  then
-                     Build_Itype_Reference (Def_Id, Parent (P));
-                  end if;
+   procedure Process_Real_Range_Specification (Def : Node_Id) is
+      Spec : constant Node_Id := Real_Range_Specification (Def);
+      Lo   : Node_Id;
+      Hi   : Node_Id;
+      Err  : Boolean := False;
 
-               else
-                  Prepare_Private_Subtype_Completion (Def_Id, Related_Nod);
-               end if;
+      procedure Analyze_Bound (N : Node_Id);
+      --  Analyze and check one bound
 
-            when Concurrent_Kind  =>
-               Constrain_Concurrent (Def_Id, S,
-                 Related_Nod, Related_Id, Suffix);
+      -------------------
+      -- Analyze_Bound --
+      -------------------
 
-            when others =>
-               Error_Msg_N ("invalid subtype mark in subtype indication", S);
-         end case;
+      procedure Analyze_Bound (N : Node_Id) is
+      begin
+         Analyze_And_Resolve (N, Any_Real);
 
-         --  Size and Convention are always inherited from the base type
+         if not Is_OK_Static_Expression (N) then
+            Flag_Non_Static_Expr
+              ("bound in real type definition is not static!", N);
+            Err := True;
+         end if;
+      end Analyze_Bound;
 
-         Set_Size_Info  (Def_Id,            (Subtype_Mark_Id));
-         Set_Convention (Def_Id, Convention (Subtype_Mark_Id));
+   --  Start of processing for Process_Real_Range_Specification
 
-         return Def_Id;
+   begin
+      if Present (Spec) then
+         Lo := Low_Bound (Spec);
+         Hi := High_Bound (Spec);
+         Analyze_Bound (Lo);
+         Analyze_Bound (Hi);
+
+         --  If error, clear away junk range specification
+
+         if Err then
+            Set_Real_Range_Specification (Def, Empty);
+         end if;
       end if;
-   end Process_Subtype;
+   end Process_Real_Range_Specification;
 
-   ---------------------------------------
-   -- Check_Anonymous_Access_Components --
-   ---------------------------------------
+   ---------------------
+   -- Process_Subtype --
+   ---------------------
 
-   procedure Check_Anonymous_Access_Components
-      (Typ_Decl  : Node_Id;
-       Typ       : Entity_Id;
-       Prev      : Entity_Id;
-       Comp_List : Node_Id)
+   function Process_Subtype
+     (S           : Node_Id;
+      Related_Nod : Node_Id;
+      Related_Id  : Entity_Id := Empty;
+      Suffix      : Character := ' ') return Entity_Id
    is
-      Loc         : constant Source_Ptr := Sloc (Typ_Decl);
-      Anon_Access : Entity_Id;
-      Acc_Def     : Node_Id;
-      Comp        : Node_Id;
-      Comp_Def    : Node_Id;
-      Decl        : Node_Id;
-      Type_Def    : Node_Id;
+      P               : Node_Id;
+      Def_Id          : Entity_Id;
+      Error_Node      : Node_Id;
+      Full_View_Id    : Entity_Id;
+      Subtype_Mark_Id : Entity_Id;
 
-      procedure Build_Incomplete_Type_Declaration;
-      --  If the record type contains components that include an access to the
-      --  current record, then create an incomplete type declaration for the
-      --  record, to be used as the designated type of the anonymous access.
-      --  This is done only once, and only if there is no previous partial
-      --  view of the type.
+      May_Have_Null_Exclusion : Boolean;
 
-      function Designates_T (Subt : Node_Id) return Boolean;
-      --  Check whether a node designates the enclosing record type, or 'Class
-      --  of that type
+      procedure Check_Incomplete (T : Entity_Id);
+      --  Called to verify that an incomplete type is not used prematurely
 
-      function Mentions_T (Acc_Def : Node_Id) return Boolean;
-      --  Check whether an access definition includes a reference to
-      --  the enclosing record type. The reference can be a subtype mark
-      --  in the access definition itself, a 'Class attribute reference, or
-      --  recursively a reference appearing in a parameter specification
-      --  or result definition of an access_to_subprogram definition.
+      ----------------------
+      -- Check_Incomplete --
+      ----------------------
 
-      --------------------------------------
-      -- Build_Incomplete_Type_Declaration --
-      --------------------------------------
+      procedure Check_Incomplete (T : Entity_Id) is
+      begin
+         --  Ada 2005 (AI-412): Incomplete subtypes are legal
 
-      procedure Build_Incomplete_Type_Declaration is
-         Decl  : Node_Id;
-         Inc_T : Entity_Id;
-         H     : Entity_Id;
+         if Ekind (Root_Type (Entity (T))) = E_Incomplete_Type
+           and then
+             not (Ada_Version >= Ada_2005
+                   and then
+                     (Nkind (Parent (T)) = N_Subtype_Declaration
+                       or else (Nkind (Parent (T)) = N_Subtype_Indication
+                                 and then Nkind (Parent (Parent (T))) =
+                                                   N_Subtype_Declaration)))
+         then
+            Error_Msg_N ("invalid use of type before its full declaration", T);
+         end if;
+      end Check_Incomplete;
 
-         --  Is_Tagged indicates whether the type is tagged. It is tagged if
-         --  it's "is new ... with record" or else "is tagged record ...".
+   --  Start of processing for Process_Subtype
 
-         Is_Tagged : constant Boolean :=
-             (Nkind (Type_Definition (Typ_Decl)) = N_Derived_Type_Definition
-                 and then
-                   Present
-                     (Record_Extension_Part (Type_Definition (Typ_Decl))))
-           or else
-             (Nkind (Type_Definition (Typ_Decl)) = N_Record_Definition
-                 and then Tagged_Present (Type_Definition (Typ_Decl)));
+   begin
+      --  Case of no constraints present
 
-      begin
-         --  If there is a previous partial view, no need to create a new one
-         --  If the partial view, given by Prev, is incomplete,  If Prev is
-         --  a private declaration, full declaration is flagged accordingly.
+      if Nkind (S) /= N_Subtype_Indication then
+         Find_Type (S);
+         Check_Incomplete (S);
+         P := Parent (S);
 
-         if Prev /= Typ then
-            if Is_Tagged then
-               Make_Class_Wide_Type (Prev);
-               Set_Class_Wide_Type (Typ, Class_Wide_Type (Prev));
-               Set_Etype (Class_Wide_Type (Typ), Typ);
-            end if;
+         --  Ada 2005 (AI-231): Static check
+
+         if Ada_Version >= Ada_2005
+           and then Present (P)
+           and then Null_Exclusion_Present (P)
+           and then Nkind (P) /= N_Access_To_Object_Definition
+           and then not Is_Access_Type (Entity (S))
+         then
+            Error_Msg_N ("`NOT NULL` only allowed for an access type", S);
+         end if;
 
-            return;
+         --  The following is ugly, can't we have a range or even a flag???
 
-         elsif Has_Private_Declaration (Typ) then
+         May_Have_Null_Exclusion :=
+           Nkind_In (P, N_Access_Definition,
+                        N_Access_Function_Definition,
+                        N_Access_Procedure_Definition,
+                        N_Access_To_Object_Definition,
+                        N_Allocator,
+                        N_Component_Definition)
+             or else
+           Nkind_In (P, N_Derived_Type_Definition,
+                        N_Discriminant_Specification,
+                        N_Formal_Object_Declaration,
+                        N_Object_Declaration,
+                        N_Object_Renaming_Declaration,
+                        N_Parameter_Specification,
+                        N_Subtype_Declaration);
 
-            --  If we refer to T'Class inside T, and T is the completion of a
-            --  private type, then we need to make sure the class-wide type
-            --  exists.
+         --  Create an Itype that is a duplicate of Entity (S) but with the
+         --  null-exclusion attribute.
 
-            if Is_Tagged then
-               Make_Class_Wide_Type (Typ);
-            end if;
+         if May_Have_Null_Exclusion
+           and then Is_Access_Type (Entity (S))
+           and then Null_Exclusion_Present (P)
 
-            return;
+            --  No need to check the case of an access to object definition.
+            --  It is correct to define double not-null pointers.
 
-         --  If there was a previous anonymous access type, the incomplete
-         --  type declaration will have been created already.
+            --  Example:
+            --     type Not_Null_Int_Ptr is not null access Integer;
+            --     type Acc is not null access Not_Null_Int_Ptr;
 
-         elsif Present (Current_Entity (Typ))
-           and then Ekind (Current_Entity (Typ)) = E_Incomplete_Type
-           and then Full_View (Current_Entity (Typ)) = Typ
+           and then Nkind (P) /= N_Access_To_Object_Definition
          then
-            if Is_Tagged
-              and then Comes_From_Source (Current_Entity (Typ))
-              and then not Is_Tagged_Type (Current_Entity (Typ))
-            then
-               Make_Class_Wide_Type (Typ);
-               Error_Msg_N
-                 ("incomplete view of tagged type should be declared tagged??",
-                  Parent (Current_Entity (Typ)));
-            end if;
-            return;
+            if Can_Never_Be_Null (Entity (S)) then
+               case Nkind (Related_Nod) is
+                  when N_Full_Type_Declaration =>
+                     if Nkind (Type_Definition (Related_Nod))
+                       in N_Array_Type_Definition
+                     then
+                        Error_Node :=
+                          Subtype_Indication
+                            (Component_Definition
+                             (Type_Definition (Related_Nod)));
+                     else
+                        Error_Node :=
+                          Subtype_Indication (Type_Definition (Related_Nod));
+                     end if;
 
-         else
-            Inc_T := Make_Defining_Identifier (Loc, Chars (Typ));
-            Decl  := Make_Incomplete_Type_Declaration (Loc, Inc_T);
+                  when N_Subtype_Declaration =>
+                     Error_Node := Subtype_Indication (Related_Nod);
 
-            --  Type has already been inserted into the current scope. Remove
-            --  it, and add incomplete declaration for type, so that subsequent
-            --  anonymous access types can use it. The entity is unchained from
-            --  the homonym list and from immediate visibility. After analysis,
-            --  the entity in the incomplete declaration becomes immediately
-            --  visible in the record declaration that follows.
+                  when N_Object_Declaration =>
+                     Error_Node := Object_Definition (Related_Nod);
 
-            H := Current_Entity (Typ);
+                  when N_Component_Declaration =>
+                     Error_Node :=
+                       Subtype_Indication (Component_Definition (Related_Nod));
 
-            if H = Typ then
-               Set_Name_Entity_Id (Chars (Typ), Homonym (Typ));
-            else
-               while Present (H)
-                 and then Homonym (H) /= Typ
-               loop
-                  H := Homonym (Typ);
-               end loop;
+                  when N_Allocator =>
+                     Error_Node := Expression (Related_Nod);
 
-               Set_Homonym (H, Homonym (Typ));
+                  when others =>
+                     pragma Assert (False);
+                     Error_Node := Related_Nod;
+               end case;
+
+               Error_Msg_NE
+                 ("`NOT NULL` not allowed (& already excludes null)",
+                  Error_Node,
+                  Entity (S));
             end if;
 
-            Insert_Before (Typ_Decl, Decl);
-            Analyze (Decl);
-            Set_Full_View (Inc_T, Typ);
+            Set_Etype  (S,
+              Create_Null_Excluding_Itype
+                (T           => Entity (S),
+                 Related_Nod => P));
+            Set_Entity (S, Etype (S));
+         end if;
 
-            if Is_Tagged then
+         return Entity (S);
 
-               --  Create a common class-wide type for both views, and set the
-               --  Etype of the class-wide type to the full view.
+      --  Case of constraint present, so that we have an N_Subtype_Indication
+      --  node (this node is created only if constraints are present).
 
-               Make_Class_Wide_Type (Inc_T);
-               Set_Class_Wide_Type (Typ, Class_Wide_Type (Inc_T));
-               Set_Etype (Class_Wide_Type (Typ), Typ);
-            end if;
+      else
+         Find_Type (Subtype_Mark (S));
+
+         if Nkind (Parent (S)) /= N_Access_To_Object_Definition
+           and then not
+            (Nkind (Parent (S)) = N_Subtype_Declaration
+              and then Is_Itype (Defining_Identifier (Parent (S))))
+         then
+            Check_Incomplete (Subtype_Mark (S));
          end if;
-      end Build_Incomplete_Type_Declaration;
 
-      ------------------
-      -- Designates_T --
-      ------------------
+         P := Parent (S);
+         Subtype_Mark_Id := Entity (Subtype_Mark (S));
 
-      function Designates_T (Subt : Node_Id) return Boolean is
-         Type_Id : constant Name_Id := Chars (Typ);
+         --  Explicit subtype declaration case
 
-         function Names_T (Nam : Node_Id) return Boolean;
-         --  The record type has not been introduced in the current scope
-         --  yet, so we must examine the name of the type itself, either
-         --  an identifier T, or an expanded name of the form P.T, where
-         --  P denotes the current scope.
+         if Nkind (P) = N_Subtype_Declaration then
+            Def_Id := Defining_Identifier (P);
 
-         -------------
-         -- Names_T --
-         -------------
+         --  Explicit derived type definition case
 
-         function Names_T (Nam : Node_Id) return Boolean is
-         begin
-            if Nkind (Nam) = N_Identifier then
-               return Chars (Nam) = Type_Id;
+         elsif Nkind (P) = N_Derived_Type_Definition then
+            Def_Id := Defining_Identifier (Parent (P));
 
-            elsif Nkind (Nam) = N_Selected_Component then
-               if Chars (Selector_Name (Nam)) = Type_Id then
-                  if Nkind (Prefix (Nam)) = N_Identifier then
-                     return Chars (Prefix (Nam)) = Chars (Current_Scope);
+         --  Implicit case, the Def_Id must be created as an implicit type.
+         --  The one exception arises in the case of concurrent types, array
+         --  and access types, where other subsidiary implicit types may be
+         --  created and must appear before the main implicit type. In these
+         --  cases we leave Def_Id set to Empty as a signal that Create_Itype
+         --  has not yet been called to create Def_Id.
 
-                  elsif Nkind (Prefix (Nam)) = N_Selected_Component then
-                     return Chars (Selector_Name (Prefix (Nam))) =
-                            Chars (Current_Scope);
-                  else
-                     return False;
-                  end if;
+         else
+            if Is_Array_Type (Subtype_Mark_Id)
+              or else Is_Concurrent_Type (Subtype_Mark_Id)
+              or else Is_Access_Type (Subtype_Mark_Id)
+            then
+               Def_Id := Empty;
 
-               else
-                  return False;
-               end if;
+            --  For the other cases, we create a new unattached Itype,
+            --  and set the indication to ensure it gets attached later.
 
             else
-               return False;
+               Def_Id :=
+                 Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
             end if;
-         end Names_T;
-
-      --  Start of processing for Designates_T
+         end if;
 
-      begin
-         if Nkind (Subt) = N_Identifier then
-            return Chars (Subt) = Type_Id;
+         --  If the kind of constraint is invalid for this kind of type,
+         --  then give an error, and then pretend no constraint was given.
 
-            --  Reference can be through an expanded name which has not been
-            --  analyzed yet, and which designates enclosing scopes.
+         if not Is_Valid_Constraint_Kind
+                   (Ekind (Subtype_Mark_Id), Nkind (Constraint (S)))
+         then
+            Error_Msg_N
+              ("incorrect constraint for this kind of type", Constraint (S));
 
-         elsif Nkind (Subt) = N_Selected_Component then
-            if Names_T (Subt) then
-               return True;
+            Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
 
-            --  Otherwise it must denote an entity that is already visible.
-            --  The access definition may name a subtype of the enclosing
-            --  type, if there is a previous incomplete declaration for it.
+            --  Set Ekind of orphan itype, to prevent cascaded errors
 
-            else
-               Find_Selected_Component (Subt);
-               return
-                 Is_Entity_Name (Subt)
-                   and then Scope (Entity (Subt)) = Current_Scope
-                   and then
-                     (Chars (Base_Type (Entity (Subt))) = Type_Id
-                       or else
-                         (Is_Class_Wide_Type (Entity (Subt))
-                           and then
-                             Chars (Etype (Base_Type (Entity (Subt)))) =
-                                                                  Type_Id));
+            if Present (Def_Id) then
+               Set_Ekind (Def_Id, Ekind (Any_Type));
             end if;
 
-         --  A reference to the current type may appear as the prefix of
-         --  a 'Class attribute.
-
-         elsif Nkind (Subt) = N_Attribute_Reference
-           and then Attribute_Name (Subt) = Name_Class
-         then
-            return Names_T (Prefix (Subt));
+            --  Make recursive call, having got rid of the bogus constraint
 
-         else
-            return False;
+            return Process_Subtype (S, Related_Nod, Related_Id, Suffix);
          end if;
-      end Designates_T;
 
-      ----------------
-      -- Mentions_T --
-      ----------------
+         --  Remaining processing depends on type. Select on Base_Type kind to
+         --  ensure getting to the concrete type kind in the case of a private
+         --  subtype (needed when only doing semantic analysis).
+
+         case Ekind (Base_Type (Subtype_Mark_Id)) is
+            when Access_Kind =>
+
+               --  If this is a constraint on a class-wide type, discard it.
+               --  There is currently no way to express a partial discriminant
+               --  constraint on a type with unknown discriminants. This is
+               --  a pathology that the ACATS wisely decides not to test.
+
+               if Is_Class_Wide_Type (Designated_Type (Subtype_Mark_Id)) then
+                  if Comes_From_Source (S) then
+                     Error_Msg_N
+                       ("constraint on class-wide type ignored??",
+                        Constraint (S));
+                  end if;
 
-      function Mentions_T (Acc_Def : Node_Id) return Boolean is
-         Param_Spec : Node_Id;
+                  if Nkind (P) = N_Subtype_Declaration then
+                     Set_Subtype_Indication (P,
+                        New_Occurrence_Of (Subtype_Mark_Id, Sloc (S)));
+                  end if;
 
-         Acc_Subprg : constant Node_Id :=
-                        Access_To_Subprogram_Definition (Acc_Def);
+                  return Subtype_Mark_Id;
+               end if;
 
-      begin
-         if No (Acc_Subprg) then
-            return Designates_T (Subtype_Mark (Acc_Def));
-         end if;
+               Constrain_Access (Def_Id, S, Related_Nod);
 
-         --  Component is an access_to_subprogram: examine its formals,
-         --  and result definition in the case of an access_to_function.
+               if Expander_Active
+                 and then  Is_Itype (Designated_Type (Def_Id))
+                 and then Nkind (Related_Nod) = N_Subtype_Declaration
+                 and then not Is_Incomplete_Type (Designated_Type (Def_Id))
+               then
+                  Build_Itype_Reference
+                    (Designated_Type (Def_Id), Related_Nod);
+               end if;
 
-         Param_Spec := First (Parameter_Specifications (Acc_Subprg));
-         while Present (Param_Spec) loop
-            if Nkind (Parameter_Type (Param_Spec)) = N_Access_Definition
-              and then Mentions_T (Parameter_Type (Param_Spec))
-            then
-               return True;
+            when Array_Kind =>
+               Constrain_Array (Def_Id, S, Related_Nod, Related_Id, Suffix);
 
-            elsif Designates_T (Parameter_Type (Param_Spec)) then
-               return True;
-            end if;
+            when Decimal_Fixed_Point_Kind =>
+               Constrain_Decimal (Def_Id, S);
 
-            Next (Param_Spec);
-         end loop;
+            when Enumeration_Kind =>
+               Constrain_Enumeration (Def_Id, S);
+               Inherit_Predicate_Flags (Def_Id, Subtype_Mark_Id);
 
-         if Nkind (Acc_Subprg) = N_Access_Function_Definition then
-            if Nkind (Result_Definition (Acc_Subprg)) =
-                 N_Access_Definition
-            then
-               return Mentions_T (Result_Definition (Acc_Subprg));
-            else
-               return Designates_T (Result_Definition (Acc_Subprg));
-            end if;
-         end if;
+            when Ordinary_Fixed_Point_Kind =>
+               Constrain_Ordinary_Fixed (Def_Id, S);
 
-         return False;
-      end Mentions_T;
+            when Float_Kind =>
+               Constrain_Float (Def_Id, S);
 
-   --  Start of processing for Check_Anonymous_Access_Components
+            when Integer_Kind =>
+               Constrain_Integer (Def_Id, S);
+               Inherit_Predicate_Flags (Def_Id, Subtype_Mark_Id);
 
-   begin
-      if No (Comp_List) then
-         return;
-      end if;
+            when E_Record_Type     |
+                 E_Record_Subtype  |
+                 Class_Wide_Kind   |
+                 E_Incomplete_Type =>
+               Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
 
-      Comp := First (Component_Items (Comp_List));
-      while Present (Comp) loop
-         if Nkind (Comp) = N_Component_Declaration
-           and then Present
-             (Access_Definition (Component_Definition (Comp)))
-           and then
-             Mentions_T (Access_Definition (Component_Definition (Comp)))
-         then
-            Comp_Def := Component_Definition (Comp);
-            Acc_Def :=
-              Access_To_Subprogram_Definition
-                (Access_Definition (Comp_Def));
+               if Ekind (Def_Id) = E_Incomplete_Type then
+                  Set_Private_Dependents (Def_Id, New_Elmt_List);
+               end if;
 
-            Build_Incomplete_Type_Declaration;
-            Anon_Access := Make_Temporary (Loc, 'S');
+            when Private_Kind =>
+               Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
+               Set_Private_Dependents (Def_Id, New_Elmt_List);
 
-            --  Create a declaration for the anonymous access type: either
-            --  an access_to_object or an access_to_subprogram.
+               --  In case of an invalid constraint prevent further processing
+               --  since the type constructed is missing expected fields.
 
-            if Present (Acc_Def) then
-               if Nkind (Acc_Def) = N_Access_Function_Definition then
-                  Type_Def :=
-                    Make_Access_Function_Definition (Loc,
-                      Parameter_Specifications =>
-                        Parameter_Specifications (Acc_Def),
-                      Result_Definition => Result_Definition (Acc_Def));
-               else
-                  Type_Def :=
-                    Make_Access_Procedure_Definition (Loc,
-                      Parameter_Specifications =>
-                        Parameter_Specifications (Acc_Def));
+               if Etype (Def_Id) = Any_Type then
+                  return Def_Id;
                end if;
 
-            else
-               Type_Def :=
-                 Make_Access_To_Object_Definition (Loc,
-                   Subtype_Indication =>
-                      Relocate_Node
-                        (Subtype_Mark
-                          (Access_Definition (Comp_Def))));
+               --  If the full view is that of a task with discriminants,
+               --  we must constrain both the concurrent type and its
+               --  corresponding record type. Otherwise we will just propagate
+               --  the constraint to the full view, if available.
 
-               Set_Constant_Present
-                 (Type_Def, Constant_Present (Access_Definition (Comp_Def)));
-               Set_All_Present
-                 (Type_Def, All_Present (Access_Definition (Comp_Def)));
-            end if;
+               if Present (Full_View (Subtype_Mark_Id))
+                 and then Has_Discriminants (Subtype_Mark_Id)
+                 and then Is_Concurrent_Type (Full_View (Subtype_Mark_Id))
+               then
+                  Full_View_Id :=
+                    Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
 
-            Set_Null_Exclusion_Present
-              (Type_Def,
-               Null_Exclusion_Present (Access_Definition (Comp_Def)));
+                  Set_Entity (Subtype_Mark (S), Full_View (Subtype_Mark_Id));
+                  Constrain_Concurrent (Full_View_Id, S,
+                    Related_Nod, Related_Id, Suffix);
+                  Set_Entity (Subtype_Mark (S), Subtype_Mark_Id);
+                  Set_Full_View (Def_Id, Full_View_Id);
 
-            Decl :=
-              Make_Full_Type_Declaration (Loc,
-                Defining_Identifier => Anon_Access,
-                Type_Definition     => Type_Def);
+                  --  Introduce an explicit reference to the private subtype,
+                  --  to prevent scope anomalies in gigi if first use appears
+                  --  in a nested context, e.g. a later function body.
+                  --  Should this be generated in other contexts than a full
+                  --  type declaration?
 
-            Insert_Before (Typ_Decl, Decl);
-            Analyze (Decl);
+                  if Is_Itype (Def_Id)
+                    and then
+                      Nkind (Parent (P)) = N_Full_Type_Declaration
+                  then
+                     Build_Itype_Reference (Def_Id, Parent (P));
+                  end if;
 
-            --  If an access to subprogram, create the extra formals
+               else
+                  Prepare_Private_Subtype_Completion (Def_Id, Related_Nod);
+               end if;
 
-            if Present (Acc_Def) then
-               Create_Extra_Formals (Designated_Type (Anon_Access));
+            when Concurrent_Kind  =>
+               Constrain_Concurrent (Def_Id, S,
+                 Related_Nod, Related_Id, Suffix);
 
-            --  If an access to object, preserve entity of designated type,
-            --  for ASIS use, before rewriting the component definition.
+            when others =>
+               Error_Msg_N ("invalid subtype mark in subtype indication", S);
+         end case;
 
-            else
-               declare
-                  Desig : Entity_Id;
+         --  Size and Convention are always inherited from the base type
 
-               begin
-                  Desig := Entity (Subtype_Indication (Type_Def));
+         Set_Size_Info  (Def_Id,            (Subtype_Mark_Id));
+         Set_Convention (Def_Id, Convention (Subtype_Mark_Id));
 
-                  --  If the access definition is to the current  record,
-                  --  the visible entity at this point is an  incomplete
-                  --  type. Retrieve the full view to simplify  ASIS queries
+         return Def_Id;
+      end if;
+   end Process_Subtype;
 
-                  if Ekind (Desig) = E_Incomplete_Type then
-                     Desig := Full_View (Desig);
-                  end if;
+   --------------------------------------------
+   -- Propagate_Default_Init_Cond_Attributes --
+   --------------------------------------------
 
-                  Set_Entity
-                    (Subtype_Mark (Access_Definition  (Comp_Def)), Desig);
-               end;
-            end if;
+   procedure Propagate_Default_Init_Cond_Attributes
+     (From_Typ             : Entity_Id;
+      To_Typ               : Entity_Id;
+      Parent_To_Derivation : Boolean := False;
+      Private_To_Full_View : Boolean := False)
+   is
+      procedure Remove_Default_Init_Cond_Procedure (Typ : Entity_Id);
+      --  Remove the default initial procedure (if any) from the rep chain of
+      --  type Typ.
 
-            Rewrite (Comp_Def,
-              Make_Component_Definition (Loc,
-                Subtype_Indication =>
-               New_Occurrence_Of (Anon_Access, Loc)));
+      ----------------------------------------
+      -- Remove_Default_Init_Cond_Procedure --
+      ----------------------------------------
 
-            if Ekind (Designated_Type (Anon_Access)) = E_Subprogram_Type then
-               Set_Ekind (Anon_Access, E_Anonymous_Access_Subprogram_Type);
-            else
-               Set_Ekind (Anon_Access, E_Anonymous_Access_Type);
+      procedure Remove_Default_Init_Cond_Procedure (Typ : Entity_Id) is
+         Found : Boolean := False;
+         Prev  : Entity_Id;
+         Subp  : Entity_Id;
+
+      begin
+         Prev := Typ;
+         Subp := Subprograms_For_Type (Typ);
+         while Present (Subp) loop
+            if Is_Default_Init_Cond_Procedure (Subp) then
+               Found := True;
+               exit;
             end if;
 
-            Set_Is_Local_Anonymous_Access (Anon_Access);
+            Prev := Subp;
+            Subp := Subprograms_For_Type (Subp);
+         end loop;
+
+         if Found then
+            Set_Subprograms_For_Type (Prev, Subprograms_For_Type (Subp));
+            Set_Subprograms_For_Type (Subp, Empty);
          end if;
+      end Remove_Default_Init_Cond_Procedure;
 
-         Next (Comp);
-      end loop;
+      --  Local variables
 
-      if Present (Variant_Part (Comp_List)) then
-         declare
-            V : Node_Id;
-         begin
-            V := First_Non_Pragma (Variants (Variant_Part (Comp_List)));
-            while Present (V) loop
-               Check_Anonymous_Access_Components
-                 (Typ_Decl, Typ, Prev, Component_List (V));
-               Next_Non_Pragma (V);
-            end loop;
-         end;
-      end if;
-   end Check_Anonymous_Access_Components;
+      Inherit_Procedure : Boolean := False;
 
-   ----------------------------------
-   -- Preanalyze_Assert_Expression --
-   ----------------------------------
+   --  Start of processing for Propagate_Default_Init_Cond_Attributes
 
-   procedure Preanalyze_Assert_Expression (N : Node_Id; T : Entity_Id) is
    begin
-      In_Assertion_Expr := In_Assertion_Expr + 1;
-      Preanalyze_Spec_Expression (N, T);
-      In_Assertion_Expr := In_Assertion_Expr - 1;
-   end Preanalyze_Assert_Expression;
+      if Has_Default_Init_Cond (From_Typ) then
 
-   --------------------------------
-   -- Preanalyze_Spec_Expression --
-   --------------------------------
+         --  A derived type inherits the attributes from its parent type
 
-   procedure Preanalyze_Spec_Expression (N : Node_Id; T : Entity_Id) is
-      Save_In_Spec_Expression : constant Boolean := In_Spec_Expression;
-   begin
-      In_Spec_Expression := True;
-      Preanalyze_And_Resolve (N, T);
-      In_Spec_Expression := Save_In_Spec_Expression;
-   end Preanalyze_Spec_Expression;
+         if Parent_To_Derivation then
+            Set_Has_Inherited_Default_Init_Cond (To_Typ);
+
+         --  A full view shares the attributes with its private view
+
+         else
+            Set_Has_Default_Init_Cond (To_Typ);
+         end if;
+
+         Inherit_Procedure := True;
+
+         --  Due to the order of expansion, a derived private type is processed
+         --  by two routines which both attempt to set the attributes related
+         --  to pragma Default_Initial_Condition - Build_Derived_Type and then
+         --  Process_Full_View.
+
+         --    package Pack is
+         --       type Parent_Typ is private
+         --         with Default_Initial_Condition ...;
+         --    private
+         --       type Parent_Typ is ...;
+         --    end Pack;
+
+         --    with Pack; use Pack;
+         --    package Pack_2 is
+         --       type Deriv_Typ is private
+         --         with Default_Initial_Condition ...;
+         --    private
+         --       type Deriv_Typ is new Parent_Typ;
+         --    end Pack_2;
+
+         --  When Build_Derived_Type operates, it sets the attributes on the
+         --  full view without taking into account that the private view may
+         --  define its own default initial condition procedure. This becomes
+         --  apparent in Process_Full_View which must undo some of the work by
+         --  Build_Derived_Type and propagate the attributes from the private
+         --  to the full view.
+
+         if Private_To_Full_View then
+            Set_Has_Inherited_Default_Init_Cond (To_Typ, False);
+            Remove_Default_Init_Cond_Procedure (To_Typ);
+         end if;
+
+      --  A type must inherit the default initial condition procedure from a
+      --  parent type when the parent itself is inheriting the procedure or
+      --  when it is defining one. This circuitry is also used when dealing
+      --  with the private / full view of a type.
+
+      elsif Has_Inherited_Default_Init_Cond (From_Typ)
+        or (Parent_To_Derivation
+              and Present (Get_Pragma
+                    (From_Typ, Pragma_Default_Initial_Condition)))
+      then
+         Set_Has_Inherited_Default_Init_Cond (To_Typ);
+         Inherit_Procedure := True;
+      end if;
+
+      if Inherit_Procedure
+        and then No (Default_Init_Cond_Procedure (To_Typ))
+      then
+         Set_Default_Init_Cond_Procedure
+           (To_Typ, Default_Init_Cond_Procedure (From_Typ));
+      end if;
+   end Propagate_Default_Init_Cond_Attributes;
 
    -----------------------------
    -- Record_Type_Declaration --
@@ -20253,15 +20955,13 @@ package body Sem_Ch3 is
 
       --  Normal case
 
-      if Ada_Version < Ada_2005
-        or else not Interface_Present (Def)
-      then
+      if Ada_Version < Ada_2005 or else not Interface_Present (Def) then
          if Limited_Present (Def) then
-            Check_SPARK_Restriction ("limited is not allowed", N);
+            Check_SPARK_05_Restriction ("limited is not allowed", N);
          end if;
 
          if Abstract_Present (Def) then
-            Check_SPARK_Restriction ("abstract is not allowed", N);
+            Check_SPARK_05_Restriction ("abstract is not allowed", N);
          end if;
 
          --  The flag Is_Tagged_Type might have already been set by
@@ -20273,8 +20973,12 @@ package body Sem_Ch3 is
            Tagged_Present (Def)
              or else (Serious_Errors_Detected > 0 and then Is_Tagged_Type (T));
 
-         Set_Is_Tagged_Type      (T, Is_Tagged);
-         Set_Is_Limited_Record   (T, Limited_Present (Def));
+         Set_Is_Limited_Record (T, Limited_Present (Def));
+
+         if Is_Tagged then
+            Set_Is_Tagged_Type (T, True);
+            Set_No_Tagged_Streams_Pragma (T, No_Tagged_Streams);
+         end if;
 
          --  Type is abstract if full declaration carries keyword, or if
          --  previous partial view did.
@@ -20283,7 +20987,7 @@ package body Sem_Ch3 is
                                       or else Abstract_Present (Def));
 
       else
-         Check_SPARK_Restriction ("interface is not allowed", N);
+         Check_SPARK_05_Restriction ("interface is not allowed", N);
 
          Is_Tagged := True;
          Analyze_Interface_Declaration (T, Def);
@@ -20447,13 +21151,13 @@ package body Sem_Ch3 is
             if Nkind (Ctxt) = N_Package_Body
               and then Nkind (Parent (Ctxt)) = N_Compilation_Unit
             then
-               Check_SPARK_Restriction
+               Check_SPARK_05_Restriction
                  ("type should be defined in package specification", Typ);
 
             elsif Nkind (Ctxt) /= N_Package_Specification
               or else Nkind (Parent (Parent (Ctxt))) /= N_Compilation_Unit
             then
-               Check_SPARK_Restriction
+               Check_SPARK_05_Restriction
                  ("type should be defined in library unit package", Typ);
             end if;
          end;
@@ -20482,14 +21186,14 @@ package body Sem_Ch3 is
         or else Null_Present (Component_List (Def))
       then
          if not Is_Tagged_Type (T) then
-            Check_SPARK_Restriction ("untagged record cannot be null", Def);
+            Check_SPARK_05_Restriction ("untagged record cannot be null", Def);
          end if;
 
       else
          Analyze_Declarations (Component_Items (Component_List (Def)));
 
          if Present (Variant_Part (Component_List (Def))) then
-            Check_SPARK_Restriction ("variant part is not allowed", Def);
+            Check_SPARK_05_Restriction ("variant part is not allowed", Def);
             Analyze (Variant_Part (Component_List (Def)));
          end if;
       end if;
@@ -20875,23 +21579,24 @@ package body Sem_Ch3 is
          end if;
       end if;
 
-      --  Complete both implicit base and declared first subtype entities
+      --  Complete both implicit base and declared first subtype entities. The
+      --  inheritance of the rep item chain ensures that SPARK-related pragmas
+      --  are not clobbered when the signed integer type acts as a full view of
+      --  a private type.
 
       Set_Etype          (Implicit_Base,                 Base_Typ);
-      Set_Size_Info      (Implicit_Base,                (Base_Typ));
+      Set_Size_Info      (Implicit_Base,                 Base_Typ);
       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
+      Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
 
-      Set_Ekind          (T, E_Signed_Integer_Subtype);
-      Set_Etype          (T, Implicit_Base);
-
-      Set_Scalar_Range (Implicit_Base, Scalar_Range (Base_Typ));
-
-      Set_Size_Info      (T,                (Implicit_Base));
-      Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
-      Set_Scalar_Range   (T, Def);
-      Set_RM_Size        (T, UI_From_Int (Minimum_Size (T)));
-      Set_Is_Constrained (T);
+      Set_Ekind              (T, E_Signed_Integer_Subtype);
+      Set_Etype              (T, Implicit_Base);
+      Set_Size_Info          (T, Implicit_Base);
+      Inherit_Rep_Item_Chain (T, Implicit_Base);
+      Set_Scalar_Range       (T, Def);
+      Set_RM_Size            (T, UI_From_Int (Minimum_Size (T)));
+      Set_Is_Constrained     (T);
    end Signed_Integer_Type_Declaration;
 
 end Sem_Ch3;