Skip to content

Commit d9671bb

Browse files
authored
[clang][Interp] Implement __builtin_ffs (#72988)
1 parent c4e764e commit d9671bb

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

clang/lib/AST/Interp/InterpBuiltin.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -602,6 +602,17 @@ static bool interp__builtin_rotate(InterpState &S, CodePtr OpPC,
602602
return true;
603603
}
604604

605+
static bool interp__builtin_ffs(InterpState &S, CodePtr OpPC,
606+
const InterpFrame *Frame, const Function *Func,
607+
const CallExpr *Call) {
608+
PrimType ArgT = *S.getContext().classify(Call->getArg(0)->getType());
609+
APSInt Value = peekToAPSInt(S.Stk, ArgT);
610+
611+
uint64_t N = Value.countr_zero();
612+
pushInt(S, N == Value.getBitWidth() ? 0 : N + 1);
613+
return true;
614+
}
615+
605616
bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
606617
const CallExpr *Call) {
607618
InterpFrame *Frame = S.Current;
@@ -803,6 +814,13 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
803814
return false;
804815
break;
805816

817+
case Builtin::BI__builtin_ffs:
818+
case Builtin::BI__builtin_ffsl:
819+
case Builtin::BI__builtin_ffsll:
820+
if (!interp__builtin_ffs(S, OpPC, Frame, F, Call))
821+
return false;
822+
break;
823+
806824
default:
807825
return false;
808826
}

clang/test/AST/Interp/builtin-functions.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,3 +353,13 @@ namespace rotateright {
353353
char rotateright3[__builtin_rotateright32(0x76543210, 22) == 0x50C841D9 ? 1 : -1];
354354
char rotateright4[__builtin_rotateright64(0xFEDCBA9876543210ULL, 55) == 0xB97530ECA86421FDULL ? 1 : -1];
355355
}
356+
357+
namespace ffs {
358+
char ffs1[__builtin_ffs(0) == 0 ? 1 : -1];
359+
char ffs2[__builtin_ffs(1) == 1 ? 1 : -1];
360+
char ffs3[__builtin_ffs(0xfbe71) == 1 ? 1 : -1];
361+
char ffs4[__builtin_ffs(0xfbe70) == 5 ? 1 : -1];
362+
char ffs5[__builtin_ffs(1U << (BITSIZE(int) - 1)) == BITSIZE(int) ? 1 : -1];
363+
char ffs6[__builtin_ffsl(0x10L) == 5 ? 1 : -1];
364+
char ffs7[__builtin_ffsll(0x100LL) == 9 ? 1 : -1];
365+
}

0 commit comments

Comments
 (0)