Skip to content

Update POPCOUNT macro to be type-flexible #87718

@Nuthouse01

Description

@Nuthouse01

Is your enhancement proposal related to a problem? Please describe.

The current definition of the POPCOUNT macro in gcc.h is simply #define POPCOUNT(x) __builtin_popcount(x). This only supports uint32 or smaller datatypes. When operating on a uint64 or type, the upper half of the number is truncated/ignored, leading to potential bugs.

Describe the solution you'd like

The compiler should examine the data type of x and use either __builtin_popcountll() or __builtin_popcount() as is appropriate. I envision a system very similar to the current implementation of LOG2 macro in util.h. Specifically,

#define POPCOUNT(x) (sizeof(__typeof__(x)) > 4 ? __builtin_popcountll(x) : __builtin_popcount(x))

Describe alternatives you've considered

Adding a second macro #define POPCOUNT_64(x) __builtin_popcountll(x) would also be acceptable, as way of making user code more readable and easier to remember.

Additional context

None

Metadata

Metadata

Labels

EnhancementChanges/Updates/Additions to existing featuresarea: ToolchainsToolchains

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions