[COMMITTED,14/35] ada: Add Type_Size_For function to Uintp package

Message ID 20241025091107.485741-14-poulhies@adacore.com
State Committed
Commit 77f6918222a3a9ff8bc3f6ea59656105c883f8df
Headers
Series [COMMITTED,01/35] ada: Pass parameters of full access unconstrained array types by copy in calls |

Commit Message

Marc Poulhiès Oct. 25, 2024, 9:10 a.m. UTC
  From: Eric Botcazou <ebotcazou@adacore.com>

It computes the size of an integer type that can accommodate the input.

gcc/ada/ChangeLog:

	* uintp.ads (Type_Size_For): New function declaration.
	* uintp.adb (Type_Size_For): New function body.
	* exp_imgv.adb (Rewrite_Object_Image): Call Type_Size_For to get
	the size of a narrower integer type.

Tested on x86_64-pc-linux-gnu, committed on master.

---
 gcc/ada/exp_imgv.adb |  9 ++++-----
 gcc/ada/uintp.adb    | 13 +++++++++++++
 gcc/ada/uintp.ads    |  3 +++
 3 files changed, 20 insertions(+), 5 deletions(-)
  

Patch

diff --git a/gcc/ada/exp_imgv.adb b/gcc/ada/exp_imgv.adb
index 20afebc061c..c95c46adbc0 100644
--- a/gcc/ada/exp_imgv.adb
+++ b/gcc/ada/exp_imgv.adb
@@ -2539,13 +2539,12 @@  package body Exp_Imgv is
 
          elsif Nkind (P) = N_Integer_Literal then
             declare
-               Val  : constant Uint    := Intval (P);
-               Neg  : constant Boolean := Val < Uint_0;
-               Bits : constant Nat     := Num_Bits (Val) + Boolean'Pos (Neg);
+               Val  : constant Uint := Intval (P);
+               Siz  : constant Nat  := Type_Size_For (Val);
 
             begin
-               if Bits <= System_Max_Integer_Size then
-                  Ptyp := Integer_Type_For (UI_From_Int (Bits), not Neg);
+               if Siz <= System_Max_Integer_Size then
+                  Ptyp := Integer_Type_For (UI_From_Int (Siz), Val >= Uint_0);
                end if;
             end;
          end if;
diff --git a/gcc/ada/uintp.adb b/gcc/ada/uintp.adb
index 1957928f7f6..fc548e02d57 100644
--- a/gcc/ada/uintp.adb
+++ b/gcc/ada/uintp.adb
@@ -758,6 +758,19 @@  package body Uintp is
       end if;
    end Release_And_Save;
 
+   --------------------
+   --  Type_Size_For --
+   --------------------
+
+   function Type_Size_For (Input : Valid_Uint) return Nat is
+      Neg  : constant Boolean := Input < Uint_0;
+
+   begin
+      --  Num_Bits is correct only for nonnegative values
+
+      return Num_Bits (Input) + Boolean'Pos (Neg);
+   end Type_Size_For;
+
    -------------
    -- UI_Abs --
    -------------
diff --git a/gcc/ada/uintp.ads b/gcc/ada/uintp.ads
index c80b4947185..2676ff51d30 100644
--- a/gcc/ada/uintp.ads
+++ b/gcc/ada/uintp.ads
@@ -264,6 +264,9 @@  package Uintp is
    --  function is used for capacity checks, and it can be one bit off
    --  without affecting its usage.
 
+   function Type_Size_For (Input : Valid_Uint) return Nat;
+   --  Returns the size of an integer type that can accommodate Input
+
    ---------------------
    -- Output Routines --
    ---------------------