Silverfrost Forums

Welcome to our forums

Please add new intrinsic functions that use x64 LEADZ,TRAILZ

13 Nov 2025 2:26 #32461

Paul, please consider adding new intrinsic functions that make the X64 instructions LEADZ, TRAILZ and POPCNT available to the Fortran programmer. There are several situations where such a function call can replace an entire DO loop. For example, given an integer variable v, if we wish to divide by the largest power of 2 possible, we could do

nz=trailz(v) if(nz > 0) v = ishft(v,nz)

instead of writing a loop:

WHILE (MOD(v,2).eq.0) DO v = v/2 END DO

Thank you. Of course, these new intrinsics are feasible only when targeting X64.

14 Nov 2025 7:30 #32464

mecej4 Thank you for the feedback. I will add these to the wish list.

14 Nov 2025 1:57 #32468

Thanks, Paul. The trailz function is also useful in deciding whether a four digit year is a leap year.

   integer:: yyyy, ntz
   logical :: cent, leap

    ntz  = trailz(yyyy)
    cent = mod(yyyy,100).eq.0
    if(cent)then
       leap = ntz > 3   !yrs divisible by 400
    else
       leap = ntz > 1   ! yrs divisible by 4
    endif

Surprising information from the past:

45 BC, 42 BC, 39 BC, 36 BC, 33 BC, 30 BC, 27 BC, 24 BC, 21 BC, 18 BC, 15 BC, 12 BC, 9 BC, 8 AD, 12 AD were regarded as leap years before the advent of the Gregorian calendar. See https://astro101.wwu.edu/a101_leapyear.html

16 Nov 2025 10:52 (Edited: 16 Nov 2025 2:49) #32477

Gfortran, Intel Fortran, Absoft Fortran and NAG Fortran provide TRAILZ as an intrinsic function.

Another application for TRAILZ is in rapid calculation of Collatz sequences. I am curious to know if anyone on this forum has toyed with the Collatz Conjecture.

16 Nov 2025 1:49 #32481

The functions TRAILZ, LEADZ, and POPCNT (and also POPPAR) are listed as intrinsic functions in the 2008 standard.

16 Nov 2025 2:34 #32482

Thanks, Kenneth, and I have no excuse for not being aware of those additions to F2008 in 2025, other than not running into an instance of one of them being beneficial in a Fortran program.

18 Nov 2025 3:07 #32488

These functions have now been added for the next release of FTN95 and its library.

22 Dec 2025 3:29 #32597

It has been rumoured that a POPCOUNT instruction was implemented by Cray and Thornton on the CDC6600 at the insistence of the US NSA for use in cryptographic work. Thus, we see that the second POPCOUNT was born 42 years after its big brother.

Please login to reply.