[clang] [clang]Implement the c23 stdc bit builtins (PR #185978)

Erich Keane via cfe-commits cfe-commits at lists.llvm.org
Tue Mar 31 09:50:59 PDT 2026


================
@@ -3733,6 +3733,210 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
   case Builtin::BI_rotr64:
     return emitRotate(E, true);
 
+  case Builtin::BI__builtin_stdc_leading_zeros: {
+    Value *ArgValue = EmitScalarExpr(E->getArg(0));
+    llvm::Type *ArgType = ArgValue->getType();
+    llvm::Type *ResultType = ConvertType(E->getType());
+    Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
+    Value *Result = Builder.CreateCall(F, {ArgValue, Builder.getFalse()});
+    if (Result->getType() != ResultType)
+      Result = Builder.CreateIntCast(Result, ResultType, false);
+    return RValue::get(Result);
+  }
+  case Builtin::BI__builtin_stdc_leading_ones: {
+    Value *ArgValue = EmitScalarExpr(E->getArg(0));
+    llvm::Type *ArgType = ArgValue->getType();
+    llvm::Type *ResultType = ConvertType(E->getType());
+    Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
+    Value *Result = Builder.CreateCall(
+        F, {Builder.CreateNot(ArgValue), Builder.getFalse()});
+    if (Result->getType() != ResultType)
+      Result = Builder.CreateIntCast(Result, ResultType, false);
+    return RValue::get(Result);
+  }
+  case Builtin::BI__builtin_stdc_trailing_zeros: {
+    Value *ArgValue = EmitScalarExpr(E->getArg(0));
+    llvm::Type *ArgType = ArgValue->getType();
+    llvm::Type *ResultType = ConvertType(E->getType());
+    Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
+    Value *Result = Builder.CreateCall(F, {ArgValue, Builder.getFalse()});
+    if (Result->getType() != ResultType)
----------------
erichkeane wrote:

I think we should probably still extract some functions for the common parts here, I realize I suggested moving in this direction, but this ended up being an awful amount of repetition.  

It seems like there is perhaps a a function that just takes a handful of arguments to handle a vast majority of these?  Plus perhaps leave the 'cleanups' in place/have a few functions that differ by that? 

https://github.com/llvm/llvm-project/pull/185978


More information about the cfe-commits mailing list