[clang] [Clang] Add __builtin_get_counted_by builtin (PR #102549)

via cfe-commits cfe-commits at lists.llvm.org
Tue Aug 13 02:07:18 PDT 2024


================
@@ -6590,8 +6590,34 @@ ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
     return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
                             VK_PRValue, RParenLoc, CurFPFeatureOverrides());
   }
-  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
-                               ExecConfig, IsExecConfig);
+
+  Result = BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
+                                 ExecConfig, IsExecConfig);
+
+  if (FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
+      FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_get_counted_by) {
+    if (const MemberExpr *ME = ArgExprs[0]->getMemberExpr()) {
+      bool IsFlexibleArrayMember = ME->isFlexibleArrayMemberLike(
+          Context, getLangOpts().getStrictFlexArraysLevel());
+
+      if (!ME->HasSideEffects(Context) && IsFlexibleArrayMember &&
+          ME->getMemberDecl()->getType()->isCountAttributedType()) {
+        const FieldDecl *FAMDecl = dyn_cast<FieldDecl>(ME->getMemberDecl());
+        if (const FieldDecl *CountFD = FAMDecl->FindCountedByField()) {
+          // The builtin returns a 'size_t *', however 'size_t' might not be
+          // the type of the count field. Thus we create an explicit c-style
+          // cast to ensure the proper types going forward.
+          QualType PtrTy = Context.getPointerType(CountFD->getType());
+          Result = CStyleCastExpr::Create(
----------------
Sirraide wrote:

I think the ‘proper’ way to do this might be to use `ImpCastExprToType`, but also, none of this should be necessary anymore if you implement custom type checking, at which point this can actually just return the type it’s supposed to return w/o requiring a cast.

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


More information about the cfe-commits mailing list