OSDN Git Service

2010-10-26 Jerry DeLisle <jvdelisle@gcc.gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_intr.adb
index 6eb9bed..977e335 100644 (file)
@@ -6,18 +6,17 @@
 --                                                                          --
 --                                 B o d y                                  --
 --                                                                          --
---          Copyright (C) 1992-2005, Free Software Foundation, Inc.         --
+--          Copyright (C) 1992-2010, 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- --
--- ware  Foundation;  either version 2,  or (at your option) any later ver- --
+-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
 -- for  more details.  You should have  received  a copy of the GNU General --
--- Public License  distributed with GNAT;  see file COPYING.  If not, write --
--- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
--- Boston, MA 02110-1301, USA.                                              --
+-- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
+-- http://www.gnu.org/licenses for a complete copy of the license.          --
 --                                                                          --
 -- GNAT was originally developed  by the GNAT team at  New York University. --
 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
 ------------------------------------------------------------------------------
 
 with Atree;    use Atree;
+with Checks;   use Checks;
 with Einfo;    use Einfo;
 with Elists;   use Elists;
 with Errout;   use Errout;
+with Exp_Atag; use Exp_Atag;
 with Exp_Ch4;  use Exp_Ch4;
 with Exp_Ch7;  use Exp_Ch7;
 with Exp_Ch11; use Exp_Ch11;
 with Exp_Code; use Exp_Code;
-with Exp_Disp; use Exp_Disp;
 with Exp_Fixd; use Exp_Fixd;
 with Exp_Util; use Exp_Util;
 with Freeze;   use Freeze;
 with Namet;    use Namet;
 with Nmake;    use Nmake;
 with Nlists;   use Nlists;
+with Opt;      use Opt;
 with Restrict; use Restrict;
+with Rident;   use Rident;
 with Rtsfind;  use Rtsfind;
 with Sem;      use Sem;
 with Sem_Eval; use Sem_Eval;
 with Sem_Res;  use Sem_Res;
+with Sem_Type; use Sem_Type;
 with Sem_Util; use Sem_Util;
 with Sinfo;    use Sinfo;
 with Sinput;   use Sinput;
@@ -60,6 +63,10 @@ package body Exp_Intr is
    -- Local Subprograms --
    -----------------------
 
+   procedure Expand_Binary_Operator_Call (N : Node_Id);
+   --  Expand a call to an intrinsic arithmetic operator when the operand
+   --  types or sizes are not identical.
+
    procedure Expand_Is_Negative (N : Node_Id);
    --  Expand a call to the intrinsic Is_Negative function
 
@@ -85,7 +92,7 @@ package body Exp_Intr is
    --  K is the kind for the shift node
 
    procedure Expand_Unc_Conversion (N : Node_Id; E : Entity_Id);
-   --  Expand a call to an instantiation of Unchecked_Convertion into a node
+   --  Expand a call to an instantiation of Unchecked_Conversion into a node
    --  N_Unchecked_Type_Conversion.
 
    procedure Expand_Unc_Deallocation (N : Node_Id);
@@ -95,7 +102,7 @@ package body Exp_Intr is
    procedure Expand_To_Address (N : Node_Id);
    procedure Expand_To_Pointer (N : Node_Id);
    --  Expand a call to corresponding function, declared in an instance of
-   --  System.Addess_To_Access_Conversions.
+   --  System.Address_To_Access_Conversions.
 
    procedure Expand_Source_Info (N : Node_Id; Nam : Name_Id);
    --  Rewrite the node by the appropriate string or positive constant.
@@ -105,6 +112,67 @@ package body Exp_Intr is
    --    Name_Source_Location  - expand string of form file:line
    --    Name_Enclosing_Entity - expand string  with name of enclosing entity
 
+   ---------------------------------
+   -- Expand_Binary_Operator_Call --
+   ---------------------------------
+
+   procedure Expand_Binary_Operator_Call (N : Node_Id) is
+      T1  : constant Entity_Id := Underlying_Type (Etype (Left_Opnd  (N)));
+      T2  : constant Entity_Id := Underlying_Type (Etype (Right_Opnd (N)));
+      TR  : constant Entity_Id := Etype (N);
+      T3  : Entity_Id;
+      Res : Node_Id;
+
+      Siz : constant Uint := UI_Max (Esize (T1), Esize (T2));
+      --  Maximum of operand sizes
+
+   begin
+      --  Nothing to do if the operands have the same modular type
+
+      if Base_Type (T1) = Base_Type (T2)
+        and then Is_Modular_Integer_Type (T1)
+      then
+         return;
+      end if;
+
+      --  Use Unsigned_32 for sizes of 32 or below, else Unsigned_64
+
+      if Siz > 32 then
+         T3 := RTE (RE_Unsigned_64);
+      else
+         T3 := RTE (RE_Unsigned_32);
+      end if;
+
+      --  Copy operator node, and reset type and entity fields, for
+      --  subsequent reanalysis.
+
+      Res := New_Copy (N);
+      Set_Etype (Res, T3);
+
+      case Nkind (N) is
+         when N_Op_And =>
+            Set_Entity (Res, Standard_Op_And);
+         when N_Op_Or =>
+            Set_Entity (Res, Standard_Op_Or);
+         when N_Op_Xor =>
+            Set_Entity (Res, Standard_Op_Xor);
+         when others =>
+            raise Program_Error;
+      end case;
+
+      --  Convert operands to large enough intermediate type
+
+      Set_Left_Opnd (Res,
+        Unchecked_Convert_To (T3, Relocate_Node (Left_Opnd (N))));
+      Set_Right_Opnd (Res,
+        Unchecked_Convert_To (T3, Relocate_Node (Right_Opnd (N))));
+
+      --  Analyze and resolve result formed by conversion to target type
+
+      Rewrite (N, Unchecked_Convert_To (TR, Res));
+      Analyze_And_Resolve (N, TR);
+   end Expand_Binary_Operator_Call;
+
    -----------------------------------------
    -- Expand_Dispatching_Constructor_Call --
    -----------------------------------------
@@ -115,8 +183,8 @@ package body Exp_Intr is
    --     GDC_Instance (The_Tag, Parameters'Access)
 
    --  to a class-wide conversion of a dispatching call to the actual
-   --  associated with the formal subprogram Construct, designating
-   --  The_Tag as the controlling tag of the call:
+   --  associated with the formal subprogram Construct, designating The_Tag
+   --  as the controlling tag of the call:
 
    --     T'Class (Construct'Actual (Params)) -- Controlling tag is The_Tag
 
@@ -124,8 +192,8 @@ package body Exp_Intr is
 
    --     T'Class (The_Tag.all (Construct'Actual'Index).all (Params))
 
-   --  A class-wide membership test is also generated, preceding the call,
-   --  to ensure that the controlling tag denotes a type in T'Class.
+   --  A class-wide membership test is also generated, preceding the call, to
+   --  ensure that the controlling tag denotes a type in T'Class.
 
    procedure Expand_Dispatching_Constructor_Call (N : Node_Id) is
       Loc        : constant Source_Ptr := Sloc (N);
@@ -135,8 +203,9 @@ package body Exp_Intr is
       Inst_Pkg   : constant Node_Id    := Parent (Subp_Decl);
       Act_Rename : Node_Id;
       Act_Constr : Entity_Id;
-      Result_Typ : Entity_Id;
+      Iface_Tag  : Node_Id := Empty;
       Cnstr_Call : Node_Id;
+      Result_Typ : Entity_Id;
 
    begin
       --  The subprogram is the third actual in the instantiation, and is
@@ -152,6 +221,37 @@ package body Exp_Intr is
       Act_Constr := Entity (Name (Act_Rename));
       Result_Typ := Class_Wide_Type (Etype (Act_Constr));
 
+      --  Ada 2005 (AI-251): If the result is an interface type, the function
+      --  returns a class-wide interface type (otherwise the resulting object
+      --  would be abstract!)
+
+      if Is_Interface (Etype (Act_Constr)) then
+         Set_Etype (Act_Constr, Result_Typ);
+
+         --  If the result type is not parent of Tag_Arg then we need to
+         --  locate the tag of the secondary dispatch table.
+
+         if not Is_Ancestor (Etype (Result_Typ), Etype (Tag_Arg)) then
+            pragma Assert (not Is_Interface (Etype (Tag_Arg)));
+
+            Iface_Tag :=
+              Make_Object_Declaration (Loc,
+                Defining_Identifier => Make_Temporary (Loc, 'V'),
+                Object_Definition   =>
+                  New_Reference_To (RTE (RE_Tag), Loc),
+                Expression          =>
+                  Make_Function_Call (Loc,
+                    Name => New_Reference_To (RTE (RE_Secondary_Tag), Loc),
+                    Parameter_Associations => New_List (
+                      Relocate_Node (Tag_Arg),
+                      New_Reference_To
+                        (Node (First_Elmt (Access_Disp_Table
+                                            (Etype (Etype (Act_Constr))))),
+                         Loc))));
+            Insert_Action (N, Iface_Tag);
+         end if;
+      end if;
+
       --  Create the call to the actual Constructor function
 
       Cnstr_Call :=
@@ -160,8 +260,18 @@ package body Exp_Intr is
           Parameter_Associations => New_List (Relocate_Node (Param_Arg)));
 
       --  Establish its controlling tag from the tag passed to the instance
+      --  The tag may be given by a function call, in which case a temporary
+      --  should be generated now, to prevent out-of-order insertions during
+      --  the expansion of that call when stack-checking is enabled.
 
-      Set_Controlling_Argument (Cnstr_Call, Relocate_Node (Tag_Arg));
+      if Present (Iface_Tag) then
+         Set_Controlling_Argument (Cnstr_Call,
+           New_Occurrence_Of (Defining_Identifier (Iface_Tag), Loc));
+      else
+         Remove_Side_Effects (Tag_Arg);
+         Set_Controlling_Argument (Cnstr_Call,
+           Relocate_Node (Tag_Arg));
+      end if;
 
       --  Rewrite and analyze the call to the instance as a class-wide
       --  conversion of the call to the actual constructor.
@@ -169,32 +279,80 @@ package body Exp_Intr is
       Rewrite (N, Convert_To (Result_Typ, Cnstr_Call));
       Analyze_And_Resolve (N, Etype (Act_Constr));
 
+      --  Do not generate a run-time check on the built object if tag
+      --  checks are suppressed for the result type or VM_Target /= No_VM
+
+      if Tag_Checks_Suppressed (Etype (Result_Typ))
+        or else not Tagged_Type_Expansion
+      then
+         null;
+
       --  Generate a class-wide membership test to ensure that the call's tag
-      --  argument denotes a type within the class.
-
-      Insert_Action (N,
-        Make_Implicit_If_Statement (N,
-          Condition =>
-            Make_Op_Not (Loc,
-              Make_DT_Access_Action (Result_Typ,
-                 Action => CW_Membership,
-                 Args   => New_List (
-                   Duplicate_Subexpr (Tag_Arg),
-                   New_Reference_To (
-                     Node (First_Elmt (Access_Disp_Table (
-                                         Root_Type (Result_Typ)))), Loc)))),
-          Then_Statements =>
-            New_List (Make_Raise_Statement (Loc,
-                        New_Occurrence_Of (RTE (RE_Tag_Error), Loc)))));
+      --  argument denotes a type within the class. We must keep separate the
+      --  case in which the Result_Type of the constructor function is a tagged
+      --  type from the case in which it is an abstract interface because the
+      --  run-time subprogram required to check these cases differ (and have
+      --  one difference in their parameters profile).
+
+      --  Call CW_Membership if the Result_Type is a tagged type to look for
+      --  the tag in the table of ancestor tags.
+
+      elsif not Is_Interface (Result_Typ) then
+         declare
+            Obj_Tag_Node : Node_Id := Duplicate_Subexpr (Tag_Arg);
+            CW_Test_Node : Node_Id;
+
+         begin
+            Build_CW_Membership (Loc,
+              Obj_Tag_Node => Obj_Tag_Node,
+              Typ_Tag_Node =>
+                New_Reference_To (
+                   Node (First_Elmt (Access_Disp_Table (
+                                       Root_Type (Result_Typ)))), Loc),
+              Related_Nod => N,
+              New_Node    => CW_Test_Node);
+
+            Insert_Action (N,
+              Make_Implicit_If_Statement (N,
+                Condition =>
+                  Make_Op_Not (Loc, CW_Test_Node),
+                Then_Statements =>
+                  New_List (Make_Raise_Statement (Loc,
+                              New_Occurrence_Of (RTE (RE_Tag_Error), Loc)))));
+         end;
+
+      --  Call IW_Membership test if the Result_Type is an abstract interface
+      --  to look for the tag in the table of interface tags.
+
+      else
+         Insert_Action (N,
+           Make_Implicit_If_Statement (N,
+             Condition =>
+               Make_Op_Not (Loc,
+                 Make_Function_Call (Loc,
+                    Name => New_Occurrence_Of (RTE (RE_IW_Membership), Loc),
+                    Parameter_Associations => New_List (
+                      Make_Attribute_Reference (Loc,
+                        Prefix         => Duplicate_Subexpr (Tag_Arg),
+                        Attribute_Name => Name_Address),
+
+                      New_Reference_To (
+                        Node (First_Elmt (Access_Disp_Table (
+                                            Root_Type (Result_Typ)))), Loc)))),
+             Then_Statements =>
+               New_List (
+                 Make_Raise_Statement (Loc,
+                   Name => New_Occurrence_Of (RTE (RE_Tag_Error), Loc)))));
+      end if;
    end Expand_Dispatching_Constructor_Call;
 
    ---------------------------
    -- Expand_Exception_Call --
    ---------------------------
 
-   --  If the function call is not within an exception handler, then the
-   --  call is replaced by a null string. Otherwise the appropriate routine
-   --  in Ada.Exceptions is called passing the choice parameter specification
+   --  If the function call is not within an exception handler, then the call
+   --  is replaced by a null string. Otherwise the appropriate routine in
+   --  Ada.Exceptions is called passing the choice parameter specification
    --  from the enclosing handler. If the enclosing handler lacks a choice
    --  parameter, then one is supplied.
 
@@ -219,13 +377,19 @@ package body Exp_Intr is
          --  Case of in exception handler
 
          elsif Nkind (P) = N_Exception_Handler then
-            if No (Choice_Parameter (P)) then
 
-               --  If no choice parameter present, then put one there. Note
-               --  that we do not need to put it on the entity chain, since
-               --  no one will be referencing it by normal visibility methods.
+            --  Handler cannot be used for a local raise, and furthermore, this
+            --  is a violation of the No_Exception_Propagation restriction.
+
+            Set_Local_Raise_Not_OK (P);
+            Check_Restriction (No_Exception_Propagation, N);
 
-               E := Make_Defining_Identifier (Loc, New_Internal_Name ('E'));
+            --  If no choice parameter present, then put one there. Note that
+            --  we do not need to put it on the entity chain, since no one will
+            --  be referencing it by normal visibility methods.
+
+            if No (Choice_Parameter (P)) then
+               E := Make_Temporary (Loc, 'E');
                Set_Choice_Parameter (P, E);
                Set_Ekind (E, E_Variable);
                Set_Etype (E, RTE (RE_Exception_Occurrence));
@@ -262,11 +426,9 @@ package body Exp_Intr is
       Loc : constant Source_Ptr := Sloc (N);
       Ent : constant Entity_Id  := Entity (Name (N));
       Str : constant Node_Id    := First_Actual (N);
-      Dum : Entity_Id;
+      Dum : constant Entity_Id  := Make_Temporary (Loc, 'D');
 
    begin
-      Dum := Make_Defining_Identifier (Loc, New_Internal_Name ('D'));
-
       Insert_Actions (N, New_List (
         Make_Object_Declaration (Loc,
           Defining_Identifier => Dum,
@@ -289,8 +451,8 @@ package body Exp_Intr is
       Rewrite (N,
         Unchecked_Convert_To (Etype (Ent),
           Make_Attribute_Reference (Loc,
-            Attribute_Name => Name_Address,
-            Prefix => Make_Identifier (Loc, Chars (Dum)))));
+            Prefix         => Make_Identifier (Loc, Chars (Dum)),
+            Attribute_Name => Name_Address)));
 
       Analyze_And_Resolve (N, Etype (Ent));
    end Expand_Import_Call;
@@ -303,6 +465,13 @@ package body Exp_Intr is
       Nam : Name_Id;
 
    begin
+      --  If an external name is specified for the intrinsic, it is handled
+      --  by the back-end: leave the call node unchanged for now.
+
+      if Present (Interface_Name (E)) then
+         return;
+      end if;
+
       --  If the intrinsic subprogram is generic, gets its original name
 
       if Present (Parent (E))
@@ -383,6 +552,9 @@ package body Exp_Intr is
       elsif Present (Alias (E)) then
          Expand_Intrinsic_Call (N,  Alias (E));
 
+      elsif Nkind (N) in N_Binary_Op then
+         Expand_Binary_Operator_Call (N);
+
          --  The only other case is where an external name was specified,
          --  since this is the only way that an otherwise unrecognized
          --  name could escape the checking in Sem_Prag. Nothing needs
@@ -569,6 +741,8 @@ package body Exp_Intr is
       --  String cases
 
       else
+         Name_Len := 0;
+
          case Nam is
             when Name_File =>
                Get_Decoded_Name_String
@@ -578,12 +752,10 @@ package body Exp_Intr is
                Build_Location_String (Loc);
 
             when Name_Enclosing_Entity =>
-               Name_Len := 0;
-
-               Ent := Current_Scope;
 
                --  Skip enclosing blocks to reach enclosing unit
 
+               Ent := Current_Scope;
                while Present (Ent) loop
                   exit when Ekind (Ent) /= E_Block
                     and then Ekind (Ent) /= E_Loop;
@@ -592,7 +764,6 @@ package body Exp_Intr is
 
                --  Ent now points to the relevant defining entity
 
-               Name_Len := 0;
                Write_Entity_Name (Ent);
 
             when others =>
@@ -600,7 +771,8 @@ package body Exp_Intr is
          end case;
 
          Rewrite (N,
-           Make_String_Literal (Loc, Strval => String_From_Name_Buffer));
+           Make_String_Literal (Loc,
+             Strval => String_From_Name_Buffer));
          Analyze_And_Resolve (N, Standard_String);
       end if;
 
@@ -697,7 +869,7 @@ package body Exp_Intr is
       Rtyp  : constant Entity_Id  := Underlying_Type (Root_Type (Typ));
       Pool  : constant Entity_Id  := Associated_Storage_Pool (Rtyp);
 
-      Desig_T   : constant Entity_Id  := Designated_Type (Typ);
+      Desig_T   : constant Entity_Id := Designated_Type (Typ);
       Gen_Code  : Node_Id;
       Free_Node : Node_Id;
       Deref     : Node_Id;
@@ -705,12 +877,22 @@ package body Exp_Intr is
       Free_Cod  : List_Id;
       Blk       : Node_Id;
 
+      Arg_Known_Non_Null : constant Boolean := Known_Non_Null (N);
+      --  This captures whether we know the argument to be non-null so that
+      --  we can avoid the test. The reason that we need to capture this is
+      --  that we analyze some generated statements before properly attaching
+      --  them to the tree, and that can disturb current value settings.
+
    begin
-      if No_Pool_Assigned (Rtyp) then
-         Error_Msg_N ("?deallocation from empty storage pool", N);
+      --  Nothing to do if we know the argument is null
+
+      if Known_Null (N) then
+         return;
       end if;
 
-      if Controlled_Type (Desig_T) then
+      --  Processing for pointer to controlled type
+
+      if Needs_Finalization (Desig_T) then
          Deref :=
            Make_Explicit_Dereference (Loc,
              Prefix => Duplicate_Subexpr_No_Checks (Arg));
@@ -761,6 +943,11 @@ package body Exp_Intr is
               (Handled_Statement_Sequence (Blk), Entity (Identifier (Blk)));
             Append (Blk, Stmts);
 
+            --  We kill saved current values, since analyzing statements not
+            --  properly attached to the tree can set wrong current values.
+
+            Kill_Current_Values;
+
          else
             Append_List_To (Stmts, Free_Cod);
          end if;
@@ -841,6 +1028,10 @@ package body Exp_Intr is
       Append_To (Stmts, Free_Node);
       Set_Storage_Pool (Free_Node, Pool);
 
+      --  Attach to tree before analysis of generated subtypes below.
+
+      Set_Parent (Stmts, Parent (N));
+
       --  Deal with storage pool
 
       if Present (Pool) then
@@ -899,75 +1090,49 @@ package body Exp_Intr is
                   D_Type := Entity (D_Subtyp);
 
                else
-                  D_Type := Make_Defining_Identifier (Loc,
-                              New_Internal_Name ('A'));
-                  Insert_Action (N,
+                  D_Type := Make_Temporary (Loc, 'A');
+                  Insert_Action (Deref,
                     Make_Subtype_Declaration (Loc,
                       Defining_Identifier => D_Type,
                       Subtype_Indication  => D_Subtyp));
-                  Freeze_Itype (D_Type, N);
-
                end if;
 
+               --  Force freezing at the point of the dereference. For the
+               --  class wide case, this avoids having the subtype frozen
+               --  before the equivalent type.
+
+               Freeze_Itype (D_Type, Deref);
+
                Set_Actual_Designated_Subtype (Free_Node, D_Type);
             end;
 
          end if;
       end if;
 
-      Set_Expression (Free_Node, Free_Arg);
-
-      --  Make implicit if statement. We omit this if we are the then part
-      --  of a test of the form:
-
-      --    if not (Arg = null) then
+      --  Ada 2005 (AI-251): In case of abstract interface type we must
+      --  displace the pointer to reference the base of the object to
+      --  deallocate its memory, unless we're targetting a VM, in which case
+      --  no special processing is required.
 
-      --  i.e. if the test is explicit in the source. Arg must be a simple
-      --  identifier for the purposes of this special test. Note that the
-      --  use of /= in the source is always transformed into the above form.
+      --  Generate:
+      --    free (Base_Address (Obj_Ptr))
 
-      declare
-         Test_Needed : Boolean := True;
-         P           : constant Node_Id := Parent (N);
-         C           : Node_Id;
-
-      begin
-         if Nkind (Arg) = N_Identifier
-           and then Nkind (P) =  N_If_Statement
-           and then First (Then_Statements (P)) = N
-         then
-            if Nkind (Condition (P)) = N_Op_Not then
-               C := Right_Opnd (Condition (P));
-
-               if Nkind (C) = N_Op_Eq
-                 and then Nkind (Left_Opnd (C)) = N_Identifier
-                 and then Chars (Arg) = Chars (Left_Opnd (C))
-                 and then Nkind (Right_Opnd (C)) = N_Null
-               then
-                  Test_Needed := False;
-               end if;
-            end if;
-         end if;
-
-         --  Generate If_Statement if needed
+      if Is_Interface (Directly_Designated_Type (Typ))
+        and then Tagged_Type_Expansion
+      then
+         Set_Expression (Free_Node,
+           Unchecked_Convert_To (Typ,
+             Make_Function_Call (Loc,
+               Name => New_Reference_To (RTE (RE_Base_Address), Loc),
+               Parameter_Associations => New_List (
+                 Unchecked_Convert_To (RTE (RE_Address), Free_Arg)))));
 
-         if Test_Needed then
-            Gen_Code :=
-              Make_Implicit_If_Statement (N,
-                Condition =>
-                  Make_Op_Ne (Loc,
-                    Left_Opnd  => Duplicate_Subexpr (Arg),
-                    Right_Opnd => Make_Null (Loc)),
-                Then_Statements => Stmts);
+      --  Generate:
+      --    free (Obj_Ptr)
 
-         else
-            Gen_Code :=
-              Make_Block_Statement (Loc,
-                Handled_Statement_Sequence =>
-                  Make_Handled_Sequence_Of_Statements (Loc,
-                    Statements => Stmts));
-         end if;
-      end;
+      else
+         Set_Expression (Free_Node, Free_Arg);
+      end if;
 
       --  Only remaining step is to set result to null, or generate a
       --  raise of constraint error if the target object is "not null".
@@ -989,6 +1154,29 @@ package body Exp_Intr is
          end;
       end if;
 
+      --  If we know the argument is non-null, then make a block statement
+      --  that contains the required statements, no need for a test.
+
+      if Arg_Known_Non_Null then
+         Gen_Code :=
+           Make_Block_Statement (Loc,
+             Handled_Statement_Sequence =>
+               Make_Handled_Sequence_Of_Statements (Loc,
+             Statements => Stmts));
+
+      --  If the argument may be null, wrap the statements inside an IF that
+      --  does an explicit test to exclude the null case.
+
+      else
+         Gen_Code :=
+           Make_Implicit_If_Statement (N,
+             Condition =>
+               Make_Op_Ne (Loc,
+                 Left_Opnd  => Duplicate_Subexpr (Arg),
+                 Right_Opnd => Make_Null (Loc)),
+             Then_Statements => Stmts);
+      end if;
+
       --  Rewrite the call
 
       Rewrite (N, Gen_Code);
@@ -1017,8 +1205,8 @@ package body Exp_Intr is
               Right_Opnd => Make_Null (Loc)),
             New_Occurrence_Of (RTE (RE_Null_Address), Loc),
             Make_Attribute_Reference (Loc,
-              Attribute_Name => Name_Address,
-              Prefix => Obj))));
+              Prefix         => Obj,
+              Attribute_Name => Name_Address))));
 
       Analyze_And_Resolve (N, RTE (RE_Address));
    end Expand_To_Address;