https://github.com/yonghong-song updated 
https://github.com/llvm/llvm-project/pull/244799

>From 174dfe01d35b37724313ce90171e1b71da10c6d3 Mon Sep 17 00:00:00 2001
From: Yonghong Song <[email protected]>
Date: Fri, 20 Nov 2026 14:40:34 -0800
Subject: [PATCH] [BPF] Accept explicit __builtin_preserve_enum_value() in case
 labels

This is a follow-up to #243338, which relocates an enumerator of a
preserve_access_index enum in a case label by comparing it with the
switch condition before the switch. An explicit
__builtin_preserve_enum_value() call in a case label was still an
error, with notes suggesting the attribute. Since a relocated case label
is already run-time code before the switch, accept the explicit call
too, so that a case label can check whether an enumerator exists, e.g.,
with libbpf's macros:
```
  switch (id) {
  case bpf_core_enum_value_exists(enum cgroup_subsys_id, hugetlb_cgrp_id) ?
       hugetlb_cgrp_id : -1:
    return 1;
  ...
  }
```
The relocated value of the enumerator is only loaded if it exists, so
the instruction that libbpf poisons for a missing enumerator is not
reachable, e.g.:
```
  r3 = 0x1 ll      CO-RE <enumval_exists> enum cgroup_subsys_id::hugetlb_cgrp_id
  if r3 == 0x0 goto +0x2
  r2 = 0x9 ll      CO-RE <enumval_value> enum cgroup_subsys_id::hugetlb_cgrp_id
  ...
  if w1 == w2 goto ...
```
To check the case value, Sema replaces an explicit call with its local
value, i.e., 1 for BPF_ENUMVAL_EXISTS and the enumerator's value in the
local enum for BPF_ENUMVAL_VALUE, in the same way as a relocated
enumerator is replaced with its DeclRefExpr, and then restores the call.
As for a relocated enumerator, the case is not checked for duplicates or
overlaps, and its local value is used for the other checks, e.g.,
-Wswitch. A call with another flag, or in a case value that is not an
integer rvalue, e.g., a compound literal, is still an error. A call in
an operand of sizeof or alignof is not relocated. As elsewhere, an
explicit call requires -g, and -fbpf-no-enum-reloc= does not affect it.

The notes for an explicit call in a case label are removed.
---
 clang/include/clang/Basic/AttrDocs.td         |  17 ++-
 .../clang/Basic/DiagnosticSemaKinds.td        |   7 -
 clang/include/clang/Sema/SemaBPF.h            |   2 +-
 clang/lib/CodeGen/CGStmt.cpp                  |  13 +-
 clang/lib/Sema/SemaBPF.cpp                    | 124 +++++++++++-------
 clang/lib/Sema/SemaStmt.cpp                   |   9 +-
 .../CodeGen/bpf-preserve-enum-value-switch.c  |  61 +++++++++
 ...f-attr-preserve-access-index-enum-switch.c |  47 ++++++-
 .../Sema/bpf-preserve-enum-value-parity.c     |  15 +--
 9 files changed, 218 insertions(+), 77 deletions(-)
 create mode 100644 clang/test/CodeGen/bpf-preserve-enum-value-switch.c

diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index bd9a40835a567e..459603215450fb 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -3105,21 +3105,28 @@ in the same way.
 If an enumerator does not exist in the kernel, libbpf poisons the instruction
 that loads its relocated value, and the verifier rejects the program if that
 instruction is reachable. A relocated case label is compared before the switch,
-so the program is rejected if the switch is reachable. A case label cannot have
-an existence check, so compare an enumerator that may not exist in an `if`
-instead, e.g., with libbpf's `bpf_core_enum_value_exists()`:
+so the program is rejected if the switch is reachable. An explicit
+`__builtin_preserve_enum_value()` call is relocated in a case label in the same
+way, so a case label can check whether an enumerator exists, e.g., with
+libbpf's `bpf_core_enum_value_exists()`:
 
 ```c
-if (bpf_core_enum_value_exists(enum E, B) && x == B)
-  return 1;
 switch (x) {
 case A:
   return 2;
+case bpf_core_enum_value_exists(enum E, B) ? B : -1:
+  return 1;
 default:
   return 0;
 }
 ```
 
+The relocated value of `B` is only loaded if `B` exists, and otherwise the case
+compares `x` with `-1`, so `-1` should not be a value of `x`. The local value 
of
+an explicit call, i.e., 1 for `bpf_core_enum_value_exists()` and the value in
+the local enum for `bpf_core_enum_value()`, is used for the checks above. An
+explicit call requires -g, as elsewhere.
+
 The `default:` label handles the enumerators that the kernel has but the local
 enum does not. `-fbpf-no-enum-reloc=` below is not an alternative for an enum
 whose values differ between kernels, since it disables the relocation for all
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index afe7b6c9efd41b..ddf1d325ac3bc2 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -13667,13 +13667,6 @@ def 
warn_preserve_access_index_enumerator_not_relocated : Warning<
   "enumerator %0 is not relocated where a constant is required, although %1 "
   "has the 'preserve_access_index' attribute">,
   InGroup<BPFEnumNotRelocated>, DefaultError;
-def note_preserve_enum_value_not_const : Note<
-  "an explicit '__builtin_preserve_enum_value' call is relocated at load time, 
"
-  "so it is not a constant">;
-def note_preserve_enum_value_case_attr : Note<
-  "a case label with an enumerator of an enum with the "
-  "'preserve_access_index' attribute is relocated, and compared like an 'if' "
-  "condition before the switch">;
 
 def err_bit_cast_non_trivially_copyable : Error<
   "'__builtin_bit_cast' %select{source|destination}0 type must be trivially 
copyable">;
diff --git a/clang/include/clang/Sema/SemaBPF.h 
b/clang/include/clang/Sema/SemaBPF.h
index ea52f78ef3d251..116acd5704aeb5 100644
--- a/clang/include/clang/Sema/SemaBPF.h
+++ b/clang/include/clang/Sema/SemaBPF.h
@@ -31,7 +31,7 @@ class SemaBPF : public SemaBase {
   void DiagnoseAnonymousPreserveAIEnums();
   Expr *BuildPreserveAIEnumeratorRef(DeclRefExpr *E);
   static bool isPreserveAIEnumeratorRef(const Expr *E);
-  static bool hasPreserveAIEnumeratorRef(const Stmt *S);
+  static bool hasPreserveEnumValue(const Stmt *S);
   void notePreserveAIEnumerator(const Expr *E);
   Expr *checkAsmImmediateOperand(Expr *E);
   Expr *keepPreserveAIEnumeratorsConstant(Expr *E);
diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 72c31c625c2eab..6b791c0b35e2e5 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -25,6 +25,7 @@
 #include "clang/Basic/DiagnosticSema.h"
 #include "clang/Basic/PrettyStackTrace.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TargetBuiltins.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/CodeGenUtils/StmtUtils.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -1748,18 +1749,24 @@ void CodeGenFunction::EmitContinueStmt(const 
ContinueStmt &S) {
 }
 
 /// Return whether S has an enumerator of a BPF preserve_access_index enum,
-/// which Sema keeps as a pseudo-object for __builtin_preserve_enum_value().
+/// which Sema keeps as a pseudo-object for __builtin_preserve_enum_value(), or
+/// an explicit __builtin_preserve_enum_value() call, not in an operand of
+/// sizeof or alignof.
 static bool hasBPFEnumeratorRef(const Stmt *S) {
-  if (!S)
+  if (!S || isa<UnaryExprOrTypeTraitExpr>(S))
     return false;
   if (const auto *POE = dyn_cast<PseudoObjectExpr>(S))
     if (const auto *DRE = dyn_cast<DeclRefExpr>(POE->getSyntacticForm());
         DRE && isa<EnumConstantDecl>(DRE->getDecl()))
       return true;
+  if (const auto *Call = dyn_cast<CallExpr>(S);
+      Call && Call->getBuiltinCallee() == BPF::BI__builtin_preserve_enum_value)
+    return true;
   return llvm::any_of(S->children(), hasBPFEnumeratorRef);
 }
 
-/// If the case value E has a relocated enumerator, see
+/// If the case value E has a relocated enumerator or an explicit
+/// __builtin_preserve_enum_value() call, see
 /// SemaBPF::verifyCaseExpr(), return E without its ConstantExpr and casts.
 /// Sema does not check it for duplicates, so it is not added to the switch 
even
 /// without debug info, where its local value is used.
diff --git a/clang/lib/Sema/SemaBPF.cpp b/clang/lib/Sema/SemaBPF.cpp
index 9690620773c971..65762c6a8e0443 100644
--- a/clang/lib/Sema/SemaBPF.cpp
+++ b/clang/lib/Sema/SemaBPF.cpp
@@ -348,14 +348,18 @@ bool SemaBPF::isPreserveAIEnumeratorRef(const Expr *E) {
 }
 
 // Return whether S has an enumerator reference built by
-// BuildPreserveAIEnumeratorRef(), e.g., a case value kept relocated by
-// verifyCaseExpr().
-bool SemaBPF::hasPreserveAIEnumeratorRef(const Stmt *S) {
-  if (!S)
+// BuildPreserveAIEnumeratorRef(), or an explicit
+// __builtin_preserve_enum_value() call not in an operand of sizeof or alignof,
+// e.g., a case value kept relocated by verifyCaseExpr().
+bool SemaBPF::hasPreserveEnumValue(const Stmt *S) {
+  if (!S || isa<UnaryExprOrTypeTraitExpr>(S))
     return false;
   if (const auto *E = dyn_cast<Expr>(S); E && isPreserveAIEnumeratorRef(E))
     return true;
-  return llvm::any_of(S->children(), hasPreserveAIEnumeratorRef);
+  if (const auto *Call = dyn_cast<CallExpr>(S);
+      Call && Call->getBuiltinCallee() == BPF::BI__builtin_preserve_enum_value)
+    return true;
+  return llvm::any_of(S->children(), hasPreserveEnumValue);
 }
 
 // If a relocated enumerator makes E non-constant, return the constant
@@ -430,12 +434,40 @@ Expr *SemaBPF::checkLocalConstantInitializer(const 
VarDecl *VD, Expr *Init) {
   return keepPreserveAIEnumeratorsConstant(Init);
 }
 
-// Replace each relocated enumerator in Slot with its DeclRefExpr, and record 
it
-// in Replaced to be restored.
+// Return the local value of an explicit __builtin_preserve_enum_value() call:
+// 1 for BPF_ENUMVAL_EXISTS, the enumerator's value for BPF_ENUMVAL_VALUE.
+static std::optional<llvm::APInt>
+getPreserveEnumValueLocalValue(ASTContext &Context, const CallExpr *Call) {
+  if (Call->getBuiltinCallee() != BPF::BI__builtin_preserve_enum_value ||
+      Call->getNumArgs() != 2 || !Call->getType()->isIntegerType())
+    return std::nullopt;
+  std::optional<llvm::APSInt> Flag =
+      Call->getArg(1)->getIntegerConstantExpr(Context);
+  if (!Flag)
+    return std::nullopt;
+  unsigned Width = Context.getIntWidth(Call->getType());
+  if (*Flag == 0)
+    return llvm::APInt(Width, 1);
+  if (*Flag != 1)
+    return std::nullopt;
+  // The argument is *(<enum_type> *)<enumerator>, see
+  // isValidPreserveEnumValueArg().
+  const auto *UO = dyn_cast<UnaryOperator>(Call->getArg(0)->IgnoreParens());
+  const auto *CE = UO ? dyn_cast<CStyleCastExpr>(UO->getSubExpr()) : nullptr;
+  const auto *DR = CE ? dyn_cast<DeclRefExpr>(CE->getSubExpr()) : nullptr;
+  const auto *ECD = DR ? dyn_cast<EnumConstantDecl>(DR->getDecl()) : nullptr;
+  if (!ECD)
+    return std::nullopt;
+  return ECD->getInitVal().extOrTrunc(Width);
+}
+
+// Replace each relocated enumerator in Slot with its DeclRefExpr, and each
+// explicit __builtin_preserve_enum_value() call with its local value, and
+// record them in Replaced to be restored.
 static void
-replaceEnumeratorRefs(Stmt *&Slot,
+replaceEnumeratorRefs(ASTContext &Context, Stmt *&Slot,
                       SmallVectorImpl<std::pair<Stmt **, Stmt *>> &Replaced) {
-  if (!Slot)
+  if (!Slot || isa<UnaryExprOrTypeTraitExpr>(Slot))
     return;
   if (auto *E = dyn_cast<Expr>(Slot);
       E && SemaBPF::isPreserveAIEnumeratorRef(E)) {
@@ -443,70 +475,68 @@ replaceEnumeratorRefs(Stmt *&Slot,
     Slot = cast<PseudoObjectExpr>(E)->getSyntacticForm();
     return;
   }
+  if (auto *Call = dyn_cast<CallExpr>(Slot)) {
+    if (std::optional<llvm::APInt> V =
+            getPreserveEnumValueLocalValue(Context, Call)) {
+      Replaced.push_back({&Slot, Slot});
+      Slot = IntegerLiteral::Create(Context, *V, Call->getType(),
+                                    Call->getBeginLoc());
+      return;
+    }
+  }
   for (Stmt *&Child : Slot->children())
-    replaceEnumeratorRefs(Child, Replaced);
-}
-
-// Return an explicit __builtin_preserve_enum_value() call in S, not in an
-// operand of sizeof or alignof.
-static const CallExpr *findPreserveEnumValueCall(const Stmt *S) {
-  if (!S || isa<UnaryExprOrTypeTraitExpr>(S))
-    return nullptr;
-  if (const auto *Call = dyn_cast<CallExpr>(S);
-      Call && Call->getBuiltinCallee() == BPF::BI__builtin_preserve_enum_value)
-    return Call;
-  for (const Stmt *Child : S->children())
-    if (const CallExpr *Call = findPreserveEnumValueCall(Child))
-      return Call;
-  return nullptr;
+    replaceEnumeratorRefs(Context, Child, Replaced);
 }
 
 // Verify that the case label value E is an integer constant expression with 
the
 // local enumerator values. A relocated enumerator in E is kept, so that
-// "case A:" behaves like "if (cond == A)". Return E in a ConstantExpr with the
-// local value, which is used to check the case values, e.g., for -Wswitch.
+// "case A:" behaves like "if (cond == A)". An explicit
+// __builtin_preserve_enum_value() call is kept in the same way, with its local
+// value, e.g., 1 for bpf_core_enum_value_exists(). Return E in a ConstantExpr
+// with the local value, which is used to check the case values, e.g., for
+// -Wswitch.
 ExprResult SemaBPF::verifyCaseExpr(Expr *E) {
+  ASTContext &Context = getASTContext();
   SmallVector<std::pair<Stmt **, Stmt *>, 4> Replaced;
   Stmt *Root = E;
-  replaceEnumeratorRefs(Root, Replaced);
+  replaceEnumeratorRefs(Context, Root, Replaced);
 
   // Check E with the local enumerator values.
   auto *ConstE = cast<Expr>(Root);
   ExprResult ER =
       SemaRef.VerifyIntegerConstantExpression(ConstE, AllowFoldKind::Allow);
-  if (ER.isInvalid()) {
-    // An explicit __builtin_preserve_enum_value() call is not a constant, but
-    // an enumerator of an enum with the attribute would be relocated here.
-    if (const CallExpr *Call = findPreserveEnumValueCall(ConstE)) {
-      Diag(Call->getBeginLoc(), diag::note_preserve_enum_value_not_const)
-          << Call->getSourceRange();
-      Diag(Call->getBeginLoc(), diag::note_preserve_enum_value_case_attr);
-    }
-    return ER;
-  }
-  if (Replaced.empty())
+  if (ER.isInvalid() || Replaced.empty())
     return ER;
 
   // Evaluate E with the local enumerator values.
   Expr::EvalResult Result;
   if (ConstE->isGLValue() ||
-      !ConstE->EvaluateAsRValue(Result, getASTContext(),
+      !ConstE->EvaluateAsRValue(Result, Context,
                                 /*InConstantContext=*/true) ||
       !Result.Val.isInt()) {
     // The value is not an integer rvalue, e.g., a compound literal folded as
-    // an extension. Keep the enumerators constants and warn.
+    // an extension. Keep the enumerators constants and warn. An explicit call
+    // cannot be kept a constant, so restore it and report that E is not a
+    // constant.
+    bool HasCall = false;
+    for (auto [Slot, Orig] : Replaced)
+      if (isa<CallExpr>(Orig)) {
+        *Slot = Orig;
+        HasCall = true;
+      }
+    if (HasCall)
+      return SemaRef.VerifyIntegerConstantExpression(E, AllowFoldKind::Allow);
     for (const auto &R : Replaced)
       warnEnumeratorNotRelocated(*this, cast<DeclRefExpr>(*R.first));
     return ER;
   }
 
-  // Restore the relocated enumerators. ActOnFinishSwitchStmt() looks through a
-  // ConstantExpr at the top of a case value to find its unpromoted type, so 
put
-  // the ConstantExpr in a no-op cast to keep its value, e.g.,
-  // NoOp(ConstantExpr(A)) for "case A:".
-  for (auto [Slot, Ref] : Replaced)
-    *Slot = Ref;
-  ASTContext &Context = getASTContext();
+  // Restore the relocated enumerators and explicit calls.
+  // ActOnFinishSwitchStmt() looks through a ConstantExpr at the top of a case
+  // value to find its unpromoted type, so put the ConstantExpr in a no-op cast
+  // to keep its value, e.g., NoOp(ConstantExpr(A)) for "case A:".
+  for (auto [Slot, Orig] : Replaced)
+    *Slot = Orig;
   Expr *CE = ConstantExpr::Create(Context, E, Result.Val);
   return ImplicitCastExpr::Create(Context, E->getType(), CK_NoOp, CE,
                                   /*BasePath=*/nullptr, VK_PRValue,
diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 2b2524972c550e..602ef09280f794 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -1433,7 +1433,8 @@ Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 
Stmt *Switch,
   typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
   CaseRangesTy CaseRanges;
 
-  // A BPF case with a relocated enumerator, see SemaBPF::verifyCaseExpr(), is
+  // A BPF case with a relocated enumerator or an explicit
+  // __builtin_preserve_enum_value() call, see SemaBPF::verifyCaseExpr(), is
   // compared before the switch, and its value is only known at load time, so
   // it is not checked for duplicates or overlaps. Its local value is used for
   // the other checks. A relocated singleton case is kept out of CaseVals until
@@ -1500,10 +1501,10 @@ Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 
Stmt *Switch,
           break;
         }
         CaseRanges.push_back(std::make_pair(LoVal, CS));
-        if (IsBPF && (SemaBPF::hasPreserveAIEnumeratorRef(Lo) ||
-                      SemaBPF::hasPreserveAIEnumeratorRef(CS->getRHS())))
+        if (IsBPF && (SemaBPF::hasPreserveEnumValue(Lo) ||
+                      SemaBPF::hasPreserveEnumValue(CS->getRHS())))
           RelocatedCaseRanges.insert(CS);
-      } else if (IsBPF && SemaBPF::hasPreserveAIEnumeratorRef(Lo))
+      } else if (IsBPF && SemaBPF::hasPreserveEnumValue(Lo))
         RelocatedCaseVals.push_back(std::make_pair(LoVal, CS));
       else
         CaseVals.push_back(std::make_pair(LoVal, CS));
diff --git a/clang/test/CodeGen/bpf-preserve-enum-value-switch.c 
b/clang/test/CodeGen/bpf-preserve-enum-value-switch.c
new file mode 100644
index 00000000000000..edfd3ae637c21f
--- /dev/null
+++ b/clang/test/CodeGen/bpf-preserve-enum-value-switch.c
@@ -0,0 +1,61 @@
+// REQUIRES: bpf-registered-target
+// RUN: %clang_cc1 -triple bpf -emit-llvm -debug-info-kind=limited 
-disable-llvm-passes \
+// RUN:   %s -o - | FileCheck %s
+// RUN: not %clang_cc1 -triple bpf -emit-llvm -disable-llvm-passes %s -o 
/dev/null 2>&1 \
+// RUN:   | FileCheck --check-prefix=NODBG %s
+
+// An explicit __builtin_preserve_enum_value() call in a case label is 
relocated
+// and compared before the switch, like an enumerator of a 
preserve_access_index
+// enum. The existence check guards the relocated value, so it is not reached
+// if the enumerator does not exist. Without debug info, the call is an error 
as
+// elsewhere.
+
+#define bpf_core_enum_value_exists(enum_type, enum_value)                      
\
+  __builtin_preserve_enum_value(*(typeof(enum_type) *)enum_value, 0)
+#define bpf_core_enum_value(enum_type, enum_value)                             
\
+  __builtin_preserve_enum_value(*(typeof(enum_type) *)enum_value, 1)
+
+enum cgroup_subsys_id { cpu_cgrp_id, memory_cgrp_id = 4, hugetlb_cgrp_id = 9 };
+
+int test(int id) {
+  switch (id) {
+  case 1:
+    return 1;
+  case bpf_core_enum_value_exists(enum cgroup_subsys_id, hugetlb_cgrp_id)
+      ? bpf_core_enum_value(enum cgroup_subsys_id, hugetlb_cgrp_id)
+      : -1:
+    return 2;
+  case bpf_core_enum_value(enum cgroup_subsys_id, memory_cgrp_id) ... 6:
+    return 3;
+  }
+  return 0;
+}
+
+// CHECK-LABEL: define dso_local i32 @test
+// CHECK: [[X:%[0-9]+]] = load i32, ptr %id.addr
+// CHECK-NEXT: [[E:%[0-9]+]] = call i64 @llvm.bpf.preserve.enum.value(i32 
{{[0-9]+}}, ptr @{{[0-9]+}}, i64 0), !dbg !{{[0-9]+}}, 
!llvm.preserve.access.index ![[ENUM:[0-9]+]]
+// CHECK-NEXT: [[B:%[0-9a-z]+]] = icmp ne i64 [[E]], 0
+// CHECK-NEXT: br i1 [[B]], label %[[TRUE:[0-9a-z.]+]], label 
%[[FALSE:[0-9a-z.]+]]
+// CHECK: [[TRUE]]:
+// CHECK-NEXT: [[V:%[0-9]+]] = call i64 @llvm.bpf.preserve.enum.value(i32 
{{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, 
!llvm.preserve.access.index ![[ENUM]]
+// CHECK: [[P:%[0-9a-z]+]] = phi i64 [ [[V]], %[[TRUE]] ], [ -1, %[[FALSE]] ]
+// CHECK-NEXT: [[T:%[0-9]+]] = trunc i64 [[P]] to i32
+// CHECK-NEXT: [[C:%[0-9]+]] = icmp eq i32 [[X]], [[T]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_H:[0-9a-z.]+]], label 
%[[D1:[0-9a-z.]+]]
+// CHECK: [[D1]]:
+// CHECK-NEXT: [[V:%[0-9]+]] = call i64 @llvm.bpf.preserve.enum.value(i32 
{{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, 
!llvm.preserve.access.index ![[ENUM]]
+// CHECK-NEXT: [[T:%[0-9]+]] = trunc i64 [[V]] to i32
+// CHECK-NEXT: [[LO:%[0-9]+]] = icmp sge i32 [[X]], [[T]]
+// CHECK-NEXT: [[HI:%[0-9]+]] = icmp sle i32 [[X]], 6
+// CHECK-NEXT: [[C:%[0-9]+]] = and i1 [[LO]], [[HI]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_M:[0-9a-z.]+]], label 
%[[D2:[0-9a-z.]+]]
+// CHECK: [[D2]]:
+// CHECK-NEXT: switch i32 [[X]], label %sw.epilog [
+// CHECK-NEXT: i32 1, label %sw.bb
+// CHECK-NEXT: ]
+// CHECK: [[BB_H]]:
+// CHECK-NEXT: store i32 2, ptr %retval
+// CHECK: [[BB_M]]:
+// CHECK-NEXT: store i32 3, ptr %retval
+
+// NODBG: error: using builtin function without -g
diff --git a/clang/test/Sema/bpf-attr-preserve-access-index-enum-switch.c 
b/clang/test/Sema/bpf-attr-preserve-access-index-enum-switch.c
index d8f0c9f64f3ab5..64ce10cf30d805 100644
--- a/clang/test/Sema/bpf-attr-preserve-access-index-enum-switch.c
+++ b/clang/test/Sema/bpf-attr-preserve-access-index-enum-switch.c
@@ -4,12 +4,16 @@
 // RUN:   -fbpf-no-enum-reloc=E %s
 
 // A relocated enumerator in a case label is not diagnosed by
-// -Wbpf-enum-not-relocated. A relocated case value is only known at load time,
+// -Wbpf-enum-not-relocated, and an explicit __builtin_preserve_enum_value()
+// call is accepted. A relocated case value is only known at load time,
 // so it is not checked for duplicates or overlaps, and a constant switch
 // condition may match it. The other checks use the local values, as with
 // -fbpf-no-enum-reloc=.
 
 enum E { A = 1, B = 4, C = 8, D = 300 } __attribute__((preserve_access_index));
+enum F { F1 = -2 };
+#define EXISTS(x) __builtin_preserve_enum_value(*(enum E *)x, 0)
+#define VALUE(x) __builtin_preserve_enum_value(*(enum E *)x, 1)
 
 int f(int i, char c, enum E e) {
   switch (i) {
@@ -27,13 +31,35 @@ int f(int i, char c, enum E e) {
     return 6;
   case 6: // noreloc-note {{previous case defined here}}
     return 7;
-  case A + __builtin_preserve_enum_value(*(enum E *)B, 1): // expected-error 
{{expression is not an integer constant expression}} expected-note {{an 
explicit '__builtin_preserve_enum_value' call is relocated at load time, so it 
is not a constant}} expected-note {{a case label with an enumerator of an enum 
with the 'preserve_access_index' attribute is relocated, and compared like an 
'if' condition before the switch}}
+  case A + __builtin_preserve_enum_value(*(enum E *)B, 1):
     return 8;
   // A compound literal is not an integer rvalue, so A is kept a constant.
   case (int){A + 10}: // reloc-error {{enumerator 'A' is not relocated where a 
constant is required, although 'enum E' has the 'preserve_access_index' 
attribute}}
     return 9;
   }
 
+  // An explicit __builtin_preserve_enum_value() call is relocated in the same
+  // way, with its local value: 1 for BPF_ENUMVAL_EXISTS, the enumerator's 
value
+  // for BPF_ENUMVAL_VALUE. Other flags and a compound literal are rejected.
+  switch (i) {
+  case 1:
+  case EXISTS(B):
+  case EXISTS(B) ? VALUE(B) : -1:
+  case 4:
+  case __builtin_preserve_enum_value(*(enum F *)F1, 1):
+  case -2:
+  case __builtin_preserve_enum_value(*(enum E *)B, 2): // expected-error 
{{expression is not an integer constant expression}}
+  case (int){VALUE(B)}: // expected-error {{expression is not an integer 
constant expression}}
+    break;
+  }
+
+  // A call in sizeof is not relocated.
+  switch (i) {
+  case sizeof(VALUE(B)): // expected-note {{previous case defined here}}
+  case 8: // expected-error {{duplicate case value '8'}}
+    break;
+  }
+
   // The cases without a relocated value are still checked.
   switch (i) {
   case 2: // expected-note {{previous case defined here}}
@@ -49,12 +75,24 @@ int f(int i, char c, enum E e) {
     break;
   }
 
+  switch (2) {
+  case EXISTS(A) + 2:
+    break;
+  }
+
   switch (e) { // expected-warning {{enumeration value 'D' not handled in 
switch}}
   case A:
   case B ... C:
     break;
   }
 
+  switch (e) { // expected-warning {{enumeration value 'D' not handled in 
switch}}
+  case A:
+  case VALUE(B) + 1: // expected-warning {{case value not in enumerated type 
'enum E'}}
+  case VALUE(B) ... C:
+    break;
+  }
+
   // A relocated range may overlap another range. 4 is B, 10 is not in enum E.
   switch (e) { // reloc-warning {{enumeration value 'D' not handled in switch}}
   case A ... C: // noreloc-note {{previous case defined here}}
@@ -66,5 +104,10 @@ int f(int i, char c, enum E e) {
   case D: // expected-warning {{overflow converting case value to switch 
condition type (300 to 44)}}
     break;
   }
+
+  switch (c) {
+  case VALUE(D): // expected-warning {{overflow converting case value to 
switch condition type (300 to 44)}}
+    break;
+  }
   return 0;
 }
diff --git a/clang/test/Sema/bpf-preserve-enum-value-parity.c 
b/clang/test/Sema/bpf-preserve-enum-value-parity.c
index 451f5e016289ae..e915186a0df20d 100644
--- a/clang/test/Sema/bpf-preserve-enum-value-parity.c
+++ b/clang/test/Sema/bpf-preserve-enum-value-parity.c
@@ -10,8 +10,7 @@
 // constant is required, it is kept a constant with a single error naming the
 // attribute (attr-error) instead of the error for the call (explicit-error).
 // A builtin argument error gets an extra note naming the attribute 
(attr-note).
-// A case label is an exception: the enumerator is relocated there, and the
-// error for the call gets notes suggesting the attribute (explicit-note).
+// Both are accepted in a case label, where they are relocated.
 #ifdef EXPLICIT
 enum E { A = 4 };
 #define X __builtin_preserve_enum_value(*(enum E *)A, 1)
@@ -41,12 +40,6 @@ void h(int);
 int rejected(int v, void *p) {
   static int s = X; // explicit-error {{initializer element is not a 
compile-time constant}} attr-error {{enumerator 'A' is not relocated where a 
constant is required, although 'enum E' has the 'preserve_access_index' 
attribute}}
   int a[8] = {[X] = 1}; // explicit-error {{expression is not an integer 
constant expression}} attr-error {{enumerator 'A' is not relocated where a 
constant is required, although 'enum E' has the 'preserve_access_index' 
attribute}}
-  switch (v) {
-  case X: // explicit-error {{expression is not an integer constant 
expression}} explicit-note {{an explicit '__builtin_preserve_enum_value' call 
is relocated at load time, so it is not a constant}} explicit-note {{a case 
label with an enumerator of an enum with the 'preserve_access_index' attribute 
is relocated, and compared like an 'if' condition before the switch}}
-    return 1;
-  case 5 ... X + 2: // explicit-error {{expression is not an integer constant 
expression}} explicit-note {{an explicit '__builtin_preserve_enum_value' call 
is relocated at load time, so it is not a constant}} explicit-note {{a case 
label with an enumerator of an enum with the 'preserve_access_index' attribute 
is relocated, and compared like an 'if' condition before the switch}}
-    return 2;
-  }
 #pragma unroll X // explicit-error {{expression is not an integer constant 
expression}} attr-error {{enumerator 'A' is not relocated where a constant is 
required, although 'enum E' has the 'preserve_access_index' attribute}}
   for (int i = 0; i < 8; i++)
     h(i);
@@ -79,6 +72,12 @@ unsigned long accepted(int v, int *p, void *d, const void 
*s) {
   case 4:
     v++;
   }
+  switch (v) {
+  case X:
+    return 1;
+  case 5 ... X + 2:
+    return 2;
+  }
   v += p[X] + (v == X) + (v && X ? X : 0) + (v << X) + k;
   v += __builtin_bswap32(X) + __builtin_expect(v, X);
   v += __builtin_constant_p(X) + sizeof(X) + _Generic(X, int: 1, default: 2);

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to