Author: yonghong-song
Date: 2026-11-20T07:02:52-08:00
New Revision: eab5f4312732b7d6e602e5b8bf250be26c86f503

URL: 
https://github.com/llvm/llvm-project/commit/eab5f4312732b7d6e602e5b8bf250be26c86f503
DIFF: 
https://github.com/llvm/llvm-project/commit/eab5f4312732b7d6e602e5b8bf250be26c86f503.diff

LOG: [BPF] Relocate enumerators in case labels and add -fbpf-no-enum-reloc= 
(#243338)

This is a follow-up to #232498, which added the preserve_access_index
attribute for enums. It resolves two points from the review.

Switch cases
------------
An enumerator in a case label was not relocated: the case label requires
a constant, so the local value was used and -Wbpf-enum-not-relocated was
reported. Now it is relocated, so `case A:` behaves like
`if (cond == A)`. For example:
```
  enum bpf_func_id { BPF_FUNC_a = 1, BPF_FUNC_b = 4 }
      __attribute__((preserve_access_index));

  int f(int id) {
    switch (id) {
    case 2:
      return 1;
    case BPF_FUNC_a:
      return 2;
    case BPF_FUNC_b ... BPF_FUNC_b + 3:
      return 3;
    }
    return 0;
  }
```
With -g, the switch condition is compared with each relocated case value
before the switch, in source order, so a relocated case is taken if its
value equals the value of another case at load time. A case range with a
relocated bound needs two comparisons, since the relocated range may be
empty. The generated code is like the following, where BPF_FUNC_a and
BPF_FUNC_b are the relocated values:
```
  int f(int id) {
    if (id == BPF_FUNC_a)
      goto L_a;
    if (id >= BPF_FUNC_b && id <= BPF_FUNC_b + 3)
      goto L_b;
    switch (id) {
    case 2:
      return 1;
    L_a:
      return 2;
    L_b:
      return 3;
    }
    return 0;
  }
```
A switch with a constant condition is not folded if it has a relocated
case label. Without -g, or in a nodebug function, the local values are
compared before the switch in the same way.

A relocated case value is only known at load time, so Sema does not
check it for duplicates or overlaps with other case values, e.g., two
`case A:` labels are not diagnosed. If it equals another case value at
load time, the order above decides which case is taken, so the second
`case A:` is never taken. For the same reason, Sema does not report that
no case matches a constant switch condition if there is a relocated
case. The other checks, e.g., for empty ranges, -Wswitch and overflow,
use the values in the local enum. The case value is a ConstantExpr with
the local value around the relocated expression, in a no-op implicit
cast since ActOnFinishSwitchStmt() looks through a top-level
ConstantExpr.

An explicit __builtin_preserve_enum_value() call in a case label is
still an error, since it is not a constant, but now has notes that say
why:
```
  error: expression is not an integer constant expression
    case __builtin_preserve_enum_value(*(enum E *)A, 1):
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  note: an explicit '__builtin_preserve_enum_value' call is relocated at
  load time, so it is not a constant
  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
```

Opt-out
-------
With -Wno-error=bpf-enum-not-relocated, an enumerator was relocated in a
runtime expression but not where a constant is required, e.g., in an
array bound, so the same enumerator could have two different values. Add
-fbpf-no-enum-reloc=<enum>[,<enum>...] to disable the relocation for the
named enums, or the typedef names of anonymous enums. Their enumerators
are always constants, and -Wbpf-enum-not-relocated is not reported for
them. E.g., with vmlinux.h:
```
  clang --target=bpf -O2 -g -fbpf-no-enum-reloc=bpf_map_type,bpf_prog_type ...
```
The driver passes the option only for BPF targets.

Conversion warnings
-------------------
-Wconversion, -Wsign-compare and the tautological comparison warnings
get the range of an expression from TryGetExprRange():

- Before this patch, it returned the range of the type of a relocated
  enumerator, e.g., int, whose value may be negative or need all 32
  bits. So -Wconversion and -Wsign-compare warned for, e.g.,
  `unsigned u = A;`, `unsigned char c = A;`, `x == A` with an unsigned
  `x`, or `case A:` in a switch on an unsigned value, though the same
  code does not warn for an enum without the attribute. With this patch,
  they do not warn if the local value fits.

- With Approximate set, i.e., when a likely range is enough, as for
  -Wconversion and -Wsign-compare, it now returns the range of the local
  value of a relocated enumerator, as if it were not relocated, like
  -Wswitch does for a relocated case value. Otherwise, as for the
  tautological comparison warnings, it still returns the range of the
  type, since the value is only known at load time. So, e.g.,
  -Wtautological-value-range-compare may warn for `(A & 0xff) > 255`,
  which is always false for any value of A, but not for `A == 11` with
  `A = 4` in the local enum, though 11 does not fit in 3 bits.

Documentation
-------------
Also document the load-time behavior of relocated case labels. If an
enumerator does not exist in the kernel, libbpf poisons the instruction
that loads its relocated value, and since a relocated case label is
compared before the switch, the verifier rejects the program if the
switch is reachable. A case label cannot have an existence check, so an
enumerator that may not exist should be compared in an `if` instead,
e.g., with libbpf's bpf_core_enum_value_exists(), and `default:` handles
the enumerators that the kernel has but the local enum does not.

Added: 
    clang/test/CodeGen/bpf-attr-preserve-access-index-enum-switch.c
    clang/test/Driver/bpf-no-enum-reloc.c
    clang/test/Sema/bpf-attr-preserve-access-index-enum-switch.c

Modified: 
    clang/include/clang/Basic/AttrDocs.td
    clang/include/clang/Basic/DiagnosticSemaKinds.td
    clang/include/clang/Basic/LangOptions.h
    clang/include/clang/Options/Options.td
    clang/include/clang/Sema/SemaBPF.h
    clang/lib/CodeGen/CGStmt.cpp
    clang/lib/CodeGen/CodeGenFunction.h
    clang/lib/Driver/ToolChains/Clang.cpp
    clang/lib/Sema/SemaBPF.cpp
    clang/lib/Sema/SemaChecking.cpp
    clang/lib/Sema/SemaStmt.cpp
    clang/test/Sema/bpf-attr-preserve-access-index-enum-constant.c
    clang/test/Sema/bpf-attr-preserve-access-index-enum-conversion.c
    clang/test/Sema/bpf-preserve-enum-value-parity.c

Removed: 
    


################################################################################
diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 060908a212f00..bd9a40835a567 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -3087,11 +3087,47 @@ so it is not a constant expression, and if -g is 
specified, its value is
 relocated. An enum defined in a struct or union with the attribute does not
 get the attribute.
 
-Where a constant is required, e.g., in an array bound, a case label, an array
-designator, the initializer of a global, static local or constexpr variable or
-an `"i"` operand of inline asm, the enumerator is not relocated and its value 
in
-the local enum is used. This is diagnosed by `-Wbpf-enum-not-relocated`, an
-error by default; `-Wno-error=` or `#pragma clang diagnostic` allows such a 
use.
+Where a constant is required, e.g., in an array bound, an array designator, the
+initializer of a global, static local or constexpr variable or an `"i"` operand
+of inline asm, the enumerator is not relocated and its value in the local enum
+is used. This is diagnosed by `-Wbpf-enum-not-relocated`, an error by default;
+`-Wno-error=` or `#pragma clang diagnostic` allows such a use.
+
+A case label of a switch is relocated, so that `case A:` behaves like
+`if (cond == A)`: the switch condition is compared with the relocated values
+before the other case labels, in source order. A relocated case label is not
+checked for duplicates or overlaps, since its value is only known at load time,
+e.g., two `case A:` labels are not diagnosed, and the second one is never 
taken.
+The values in the local enum are used for the other checks, e.g., `-Wswitch`.
+Without -g, or in a nodebug function, the values in the local enum are compared
+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()`:
+
+```c
+if (bpf_core_enum_value_exists(enum E, B) && x == B)
+  return 1;
+switch (x) {
+case A:
+  return 2;
+default:
+  return 0;
+}
+```
+
+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 
diff er between kernels, since it disables the relocation for all
+enumerators of the enum.
+
+`-fbpf-no-enum-reloc=<enum>[,<enum>...]` disables the relocation for the named
+enums, or the typedef names of anonymous enums: their enumerators are always
+constants, as if the enums did not have the attribute.
 
 The macro `__BPF_FEATURE_ENUM_PRESERVE_ACCESS_INDEX` is defined if the
 attribute is supported on enum declarations.

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index ddf1d325ac3bc..afe7b6c9efd41 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -13667,6 +13667,13 @@ 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/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index 8607fbae8d8fc..b36f4346fb156 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -515,6 +515,10 @@ class LangOptions : public LangOptionsBase {
   /// (files, functions) should or should not be instrumented.
   std::vector<std::string> ProfileListFiles;
 
+  /// Names of BPF enums whose enumerators are not relocated, from
+  /// -fbpf-no-enum-reloc=.
+  std::vector<std::string> BPFNoEnumRelocs;
+
   clang::ObjCRuntime ObjCRuntime;
 
   CoreFoundationABI CFRuntime = CoreFoundationABI::Unspecified;

diff  --git a/clang/include/clang/Options/Options.td 
b/clang/include/clang/Options/Options.td
index 6700765f6728d..8c18c00e048e0 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -2188,6 +2188,13 @@ defm borland_extensions : 
BoolFOption<"borland-extensions",
   PosFlag<SetTrue, [], [ClangOption, CC1Option],
           "Accept non-standard constructs supported by the Borland compiler">,
   NegFlag<SetFalse>>;
+def fbpf_no_enum_reloc_EQ : CommaJoined<["-"], "fbpf-no-enum-reloc=">,
+  Group<f_Group>, Flags<[TargetSpecific]>,
+  Visibility<[ClangOption, CC1Option]>, MetaVarName<"<enum>">,
+  HelpText<"Do not relocate the enumerators of the comma-separated enums, "
+           "although the enums have the preserve_access_index attribute "
+           "(BPF only)">,
+  MarshallingInfoStringVector<LangOpts<"BPFNoEnumRelocs">>;
 def fbuiltin : Flag<["-"], "fbuiltin">, Group<f_Group>,
   Visibility<[ClangOption, CLOption, DXCOption, FlangOption, FC1Option]>;
 def fbuiltin_module_map : Flag <["-"], "fbuiltin-module-map">, Group<f_Group>,

diff  --git a/clang/include/clang/Sema/SemaBPF.h 
b/clang/include/clang/Sema/SemaBPF.h
index 16d12e21e88ef..ea52f78ef3d25 100644
--- a/clang/include/clang/Sema/SemaBPF.h
+++ b/clang/include/clang/Sema/SemaBPF.h
@@ -31,10 +31,12 @@ class SemaBPF : public SemaBase {
   void DiagnoseAnonymousPreserveAIEnums();
   Expr *BuildPreserveAIEnumeratorRef(DeclRefExpr *E);
   static bool isPreserveAIEnumeratorRef(const Expr *E);
+  static bool hasPreserveAIEnumeratorRef(const Stmt *S);
   void notePreserveAIEnumerator(const Expr *E);
   Expr *checkAsmImmediateOperand(Expr *E);
   Expr *keepPreserveAIEnumeratorsConstant(Expr *E);
   Expr *checkLocalConstantInitializer(const VarDecl *VD, Expr *Init);
+  ExprResult verifyCaseExpr(Expr *E);
 
 private:
   llvm::MapVector<EnumDecl *, const BPFPreserveAccessIndexAttr *>

diff  --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 455c435266104..72c31c625c2ea 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -1747,6 +1747,99 @@ void CodeGenFunction::EmitContinueStmt(const 
ContinueStmt &S) {
   EmitBranchThroughCleanup(GetDestForLoopControlStmt(S)->ContinueBlock);
 }
 
+/// 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().
+static bool hasBPFEnumeratorRef(const Stmt *S) {
+  if (!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;
+  return llvm::any_of(S->children(), hasBPFEnumeratorRef);
+}
+
+/// If the case value E has a relocated enumerator, 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.
+static const Expr *getBPFRelocatedCaseValue(CodeGenFunction &CGF,
+                                            const Expr *E) {
+  if (!E || !CGF.getTarget().getTriple().isBPF())
+    return nullptr;
+  while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
+    E = ICE->getSubExpr();
+  const auto *CE = dyn_cast<ConstantExpr>(E);
+  if (!CE || !hasBPFEnumeratorRef(CE->getSubExpr()))
+    return nullptr;
+  return CE->getSubExpr();
+}
+
+static bool isBPFRelocatedCase(CodeGenFunction &CGF, const CaseStmt &S) {
+  return getBPFRelocatedCaseValue(CGF, S.getLHS()) ||
+         getBPFRelocatedCaseValue(CGF, S.getRHS());
+}
+
+/// Emit a case statement whose value is relocated: move the switch to a new
+/// block, and in its old block, branch to the case if the condition matches 
the
+/// relocated value, otherwise to the switch. So the relocated cases are 
checked
+/// in source order, before the other cases. E.g., with relocated A, B and C,
+///
+///   switch (x) { case 1: ... case A: ... case B ... C: ... }
+///
+/// is emitted like:
+///
+///   if (x == A) goto case_A;
+///   if (x >= B && x <= C) goto case_BC;
+///   switch (x) { case 1: ... }
+void CodeGenFunction::EmitBPFRelocatedCaseStmt(const CaseStmt &S,
+                                               ArrayRef<const Attr *> Attrs) {
+  llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
+  EmitBlockWithFallThrough(CaseDest, &S);
+
+  llvm::BasicBlock *CheckBB = SwitchInsn->getParent();
+  llvm::BasicBlock *SwitchBB = createBasicBlock("sw.dispatch");
+  CurFn->insert(std::next(CheckBB->getIterator()), SwitchBB);
+  SwitchInsn->removeFromParent();
+  SwitchInsn->insertInto(SwitchBB, SwitchBB->end());
+
+  // Emit the check at the end of CheckBB, then come back to the case body.
+  {
+    llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
+    Builder.SetInsertPoint(CheckBB);
+    ApplyDebugLocation DL(*this, S.getLHS());
+    llvm::Value *CondV = SwitchInsn->getCondition();
+    auto EmitCaseValue = [&](const Expr *E) -> llvm::Value * {
+      if (const Expr *Reloc = getBPFRelocatedCaseValue(*this, E))
+        return Builder.CreateIntCast(
+            EmitScalarExpr(Reloc), CondV->getType(),
+            Reloc->getType()->isSignedIntegerOrEnumerationType());
+      return Builder.getInt(E->EvaluateKnownConstInt(getContext()));
+    };
+
+    llvm::Value *Cond;
+    if (!S.getRHS()) {
+      Cond = Builder.CreateICmpEQ(CondV, EmitCaseValue(S.getLHS()));
+    } else {
+      // The relocated range may be empty.
+      bool IsSigned = 
S.getLHS()->getType()->isSignedIntegerOrEnumerationType();
+      llvm::Value *Lo = Builder.CreateICmp(IsSigned ? llvm::CmpInst::ICMP_SGE
+                                                    : llvm::CmpInst::ICMP_UGE,
+                                           CondV, EmitCaseValue(S.getLHS()));
+      llvm::Value *Hi = Builder.CreateICmp(IsSigned ? llvm::CmpInst::ICMP_SLE
+                                                    : llvm::CmpInst::ICMP_ULE,
+                                           CondV, EmitCaseValue(S.getRHS()));
+      Cond = Builder.CreateAnd(Lo, Hi);
+    }
+    if (SwitchLikelihood)
+      Cond = emitCondLikelihoodViaExpectIntrinsic(Cond,
+                                                  Stmt::getLikelihood(Attrs));
+    Builder.CreateCondBr(Cond, CaseDest, SwitchBB);
+  }
+
+  EmitStmt(S.getSubStmt());
+}
+
 /// EmitCaseStmtRange - If case statement range is not too big then
 /// add multiple cases to switch instruction, one for each value within
 /// the range. If range is too big then emit "if" condition check.
@@ -1848,6 +1941,11 @@ void CodeGenFunction::EmitCaseStmt(const CaseStmt &S,
     return;
   }
 
+  if (isBPFRelocatedCase(*this, S)) {
+    EmitBPFRelocatedCaseStmt(S, Attrs);
+    return;
+  }
+
   // Handle case ranges.
   if (S.getRHS()) {
     EmitCaseStmtRange(S, Attrs);
@@ -1917,7 +2015,8 @@ void CodeGenFunction::EmitCaseStmt(const CaseStmt &S,
   const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
 
   // Otherwise, iteratively add consecutive cases to this switch stmt.
-  while (NextCase && NextCase->getRHS() == nullptr) {
+  while (NextCase && NextCase->getRHS() == nullptr &&
+         !isBPFRelocatedCase(*this, *NextCase)) {
     CurCase = NextCase;
     llvm::ConstantInt *CaseVal =
       Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
@@ -2338,6 +2437,15 @@ getLikelihoodWeights(ArrayRef<Stmt::Likelihood> 
Likelihoods) {
   return Result;
 }
 
+static bool hasBPFRelocatedCase(CodeGenFunction &CGF, const SwitchStmt &S) {
+  for (const SwitchCase *SC = S.getSwitchCaseList(); SC;
+       SC = SC->getNextSwitchCase())
+    if (const auto *CS = dyn_cast<CaseStmt>(SC);
+        CS && isBPFRelocatedCase(CGF, *CS))
+      return true;
+  return false;
+}
+
 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
   // Handle nested switch statements.
   llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
@@ -2346,9 +2454,11 @@ void CodeGenFunction::EmitSwitchStmt(const SwitchStmt 
&S) {
   llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
 
   // See if we can constant fold the condition of the switch and therefore only
-  // emit the live case statement (if any) of the switch.
+  // emit the live case statement (if any) of the switch. A relocated case 
value
+  // is not known until load time.
   llvm::APSInt ConstantCondValue;
-  if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
+  if (!hasBPFRelocatedCase(*this, S) &&
+      ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
     SmallVector<const Stmt*, 4> CaseStmts;
     const SwitchCase *Case = nullptr;
     if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,

diff  --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index 9d5300d33d4d5..5cd26898890f8 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -3780,6 +3780,8 @@ class CodeGenFunction : public CodeGenTypeCache {
   void EmitDefaultStmt(const DefaultStmt &S, ArrayRef<const Attr *> Attrs);
   void EmitCaseStmt(const CaseStmt &S, ArrayRef<const Attr *> Attrs);
   void EmitCaseStmtRange(const CaseStmt &S, ArrayRef<const Attr *> Attrs);
+  void EmitBPFRelocatedCaseStmt(const CaseStmt &S,
+                                ArrayRef<const Attr *> Attrs);
   void EmitDeferStmt(const DeferStmt &S);
   void EmitAsmStmt(const AsmStmt &S);
 

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 5f6338ab12ed5..bd54a8fe442e8 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -1691,6 +1691,11 @@ void Clang::RenderTargetOptions(const llvm::Triple 
&EffectiveTriple,
   case llvm::Triple::ve:
     AddVETargetArgs(Args, CmdArgs);
     break;
+
+  case llvm::Triple::bpfel:
+  case llvm::Triple::bpfeb:
+    Args.AddAllArgs(CmdArgs, options::OPT_fbpf_no_enum_reloc_EQ);
+    break;
   }
 }
 

diff  --git a/clang/lib/Sema/SemaBPF.cpp b/clang/lib/Sema/SemaBPF.cpp
index 13b486497cf6c..9690620773c97 100644
--- a/clang/lib/Sema/SemaBPF.cpp
+++ b/clang/lib/Sema/SemaBPF.cpp
@@ -19,6 +19,7 @@
 #include "clang/Basic/TargetBuiltins.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Sema/ParsedAttr.h"
+#include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/Sema.h"
 #include "llvm/ADT/APSInt.h"
 #include <optional>
@@ -243,12 +244,23 @@ static QualType getPreserveAIEnumType(ASTContext &Context,
     return QualType();
 
   // libbpf matches relocations by type name, so an anonymous enum needs a
-  // typedef name.
-  if (ED->getDeclName())
-    return Context.getCanonicalTagType(ED);
-  if (const TypedefNameDecl *TD = ED->getTypedefNameForAnonDecl())
-    return Context.getTypeDeclType(TD);
-  return QualType();
+  // typedef name. An enum named by -fbpf-no-enum-reloc= is not relocated.
+  const TypedefNameDecl *TD = nullptr;
+  if (!ED->getDeclName()) {
+    TD = ED->getTypedefNameForAnonDecl();
+    if (!TD)
+      return QualType();
+  }
+  StringRef Name = TD ? TD->getName() : ED->getName();
+  if (llvm::is_contained(Context.getLangOpts().BPFNoEnumRelocs, Name))
+    return QualType();
+  return TD ? Context.getTypeDeclType(TD) : Context.getCanonicalTagType(ED);
+}
+
+static bool isInSwitchCaseLabel(Sema &S) {
+  const sema::FunctionScopeInfo *FSI = S.getCurFunction();
+  return S.currentEvaluationContext().IsCaseExpr && FSI &&
+         !FSI->SwitchStack.empty();
 }
 
 // Return the enumerator reference E, or, if it is relocated, a pseudo-object
@@ -263,9 +275,10 @@ Expr *SemaBPF::BuildPreserveAIEnumeratorRef(DeclRefExpr 
*E) {
     return E;
 
   // The value cannot be relocated where a constant is required: in a constant
-  // evaluated context, e.g., an array bound or a case label, or outside of a
-  // function, e.g., a global initializer. Warn, and use the enumerator's 
value.
-  if (SemaRef.isConstantEvaluatedContext() ||
+  // evaluated context, e.g., an array bound, or outside of a function, e.g., a
+  // global initializer. Warn, and use the enumerator's value. A case label is
+  // an exception, see verifyCaseExpr().
+  if ((SemaRef.isConstantEvaluatedContext() && !isInSwitchCaseLabel(SemaRef)) 
||
       SemaRef.CurContext->getRedeclContext()->isFileContext()) {
     Diag(E->getExprLoc(),
          diag::warn_preserve_access_index_enumerator_not_relocated)
@@ -334,6 +347,17 @@ bool SemaBPF::isPreserveAIEnumeratorRef(const Expr *E) {
          Call->getBuiltinCallee() == BPF::BI__builtin_preserve_enum_value;
 }
 
+// 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)
+    return false;
+  if (const auto *E = dyn_cast<Expr>(S); E && isPreserveAIEnumeratorRef(E))
+    return true;
+  return llvm::any_of(S->children(), hasPreserveAIEnumeratorRef);
+}
+
 // If a relocated enumerator makes E non-constant, return the constant
 // evaluator's note saying so.
 static std::optional<PartialDiagnosticAt>
@@ -360,6 +384,13 @@ void SemaBPF::notePreserveAIEnumerator(const Expr *E) {
     Diag(Note->first, Note->second);
 }
 
+static void warnEnumeratorNotRelocated(SemaBPF &S, const DeclRefExpr *DRE) {
+  S.Diag(DRE->getExprLoc(),
+         diag::warn_preserve_access_index_enumerator_not_relocated)
+      << DRE->getDecl() << getPreserveAIEnumType(S.getASTContext(), DRE)
+      << DRE->getSourceRange();
+}
+
 // Replace each relocated enumerator in St with its DeclRefExpr, which has the
 // same type and value kind, and warn that it is not relocated.
 static Stmt *keepEnumeratorsConstant(SemaBPF &S, Stmt *St) {
@@ -369,10 +400,7 @@ static Stmt *keepEnumeratorsConstant(SemaBPF &S, Stmt *St) 
{
       E && SemaBPF::isPreserveAIEnumeratorRef(E)) {
     auto *DRE =
         cast<DeclRefExpr>(cast<PseudoObjectExpr>(E)->getSyntacticForm());
-    S.Diag(DRE->getExprLoc(),
-           diag::warn_preserve_access_index_enumerator_not_relocated)
-        << DRE->getDecl() << getPreserveAIEnumType(S.getASTContext(), DRE)
-        << DRE->getSourceRange();
+    warnEnumeratorNotRelocated(S, DRE);
     return DRE;
   }
   for (Stmt *&Child : St->children())
@@ -402,4 +430,87 @@ 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.
+static void
+replaceEnumeratorRefs(Stmt *&Slot,
+                      SmallVectorImpl<std::pair<Stmt **, Stmt *>> &Replaced) {
+  if (!Slot)
+    return;
+  if (auto *E = dyn_cast<Expr>(Slot);
+      E && SemaBPF::isPreserveAIEnumeratorRef(E)) {
+    Replaced.push_back({&Slot, Slot});
+    Slot = cast<PseudoObjectExpr>(E)->getSyntacticForm();
+    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;
+}
+
+// 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.
+ExprResult SemaBPF::verifyCaseExpr(Expr *E) {
+  SmallVector<std::pair<Stmt **, Stmt *>, 4> Replaced;
+  Stmt *Root = E;
+  replaceEnumeratorRefs(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())
+    return ER;
+
+  // Evaluate E with the local enumerator values.
+  Expr::EvalResult Result;
+  if (ConstE->isGLValue() ||
+      !ConstE->EvaluateAsRValue(Result, getASTContext(),
+                                /*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.
+    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();
+  Expr *CE = ConstantExpr::Create(Context, E, Result.Val);
+  return ImplicitCastExpr::Create(Context, E->getType(), CK_NoOp, CE,
+                                  /*BasePath=*/nullptr, VK_PRValue,
+                                  FPOptionsOverride());
+}
+
 } // namespace clang

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index f43e87a15661d..86a66c0cbd314 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -12197,6 +12197,13 @@ static std::optional<IntRange> 
TryGetExprRange(ASTContext &C, const Expr *E,
                                                bool Approximate) {
   E = E->IgnoreParens();
 
+  // A BPF enumerator relocated at load time is not a constant. Use the range 
of
+  // its local value, as if it were not relocated, if an approximate range is
+  // allowed. Otherwise, use the range of its type, since its value is only
+  // known at load time.
+  if (Approximate && SemaBPF::isPreserveAIEnumeratorRef(E))
+    E = cast<PseudoObjectExpr>(E)->getSyntacticForm();
+
   // Try a full evaluation first.
   Expr::EvalResult result;
   if (E->EvaluateAsRValue(result, C, InConstantContext))

diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index ddace7669486e..2b2524972c550 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -33,6 +33,7 @@
 #include "clang/Sema/Ownership.h"
 #include "clang/Sema/Scope.h"
 #include "clang/Sema/ScopeInfo.h"
+#include "clang/Sema/SemaBPF.h"
 #include "clang/Sema/SemaCUDA.h"
 #include "clang/Sema/SemaHLSL.h"
 #include "clang/Sema/SemaObjC.h"
@@ -556,7 +557,9 @@ Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) 
{
 
     ExprResult ER = E;
     if (!E->isValueDependent())
-      ER = VerifyIntegerConstantExpression(E, AllowFoldKind::Allow);
+      ER = Context.getTargetInfo().getTriple().isBPF()
+               ? BPF().verifyCaseExpr(E)
+               : VerifyIntegerConstantExpression(E, AllowFoldKind::Allow);
     if (!ER.isInvalid())
       ER = DefaultLvalueConversion(ER.get());
     if (!ER.isInvalid())
@@ -1430,6 +1433,15 @@ 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
+  // 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
+  // the checks for duplicates and overlaps are done.
+  bool IsBPF = Context.getTargetInfo().getTriple().isBPF();
+  CaseValsTy RelocatedCaseVals;
+  llvm::SmallPtrSet<const CaseStmt *, 4> RelocatedCaseRanges;
+
   DefaultStmt *TheDefaultStmt = nullptr;
 
   bool CaseListIsErroneous = false;
@@ -1488,7 +1500,12 @@ Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 
Stmt *Switch,
           break;
         }
         CaseRanges.push_back(std::make_pair(LoVal, CS));
-      } else
+        if (IsBPF && (SemaBPF::hasPreserveAIEnumeratorRef(Lo) ||
+                      SemaBPF::hasPreserveAIEnumeratorRef(CS->getRHS())))
+          RelocatedCaseRanges.insert(CS);
+      } else if (IsBPF && SemaBPF::hasPreserveAIEnumeratorRef(Lo))
+        RelocatedCaseVals.push_back(std::make_pair(LoVal, CS));
+      else
         CaseVals.push_back(std::make_pair(LoVal, CS));
     }
   }
@@ -1509,7 +1526,10 @@ Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 
Stmt *Switch,
               ConstantCondValue.isSigned() == CondIsSigned));
       Diag(SwitchLoc, diag::warn_switch_default);
     }
-    bool ShouldCheckConstantCond = HasConstantCond;
+    // A relocated case may match the condition at load time.
+    bool ShouldCheckConstantCond = HasConstantCond &&
+                                   RelocatedCaseVals.empty() &&
+                                   RelocatedCaseRanges.empty();
 
     // Sort all the scalar case values so we can easily detect duplicates.
     llvm::stable_sort(CaseVals, CmpCaseVals);
@@ -1601,11 +1621,14 @@ Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 
Stmt *Switch,
 
       // Rescan the ranges, looking for overlap with singleton values and other
       // ranges.  Since the range list is sorted, we only need to compare case
-      // ranges with their neighbors.
+      // ranges with their neighbors. A relocated range is skipped.
+      std::optional<unsigned> PrevRange;
       for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
         llvm::APSInt &CRLo = CaseRanges[i].first;
         llvm::APSInt &CRHi = HiVals[i];
         CaseStmt *CR = CaseRanges[i].second;
+        if (RelocatedCaseRanges.contains(CR))
+          continue;
 
         // Check to see whether the case range overlaps with any
         // singleton cases.
@@ -1630,10 +1653,11 @@ Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 
Stmt *Switch,
 
         // Check to see if this case stmt overlaps with the subsequent
         // case range.
-        if (i && CRLo <= HiVals[i-1]) {
-          OverlapVal  = HiVals[i-1];       // Found overlap with range.
-          OverlapStmt = CaseRanges[i-1].second;
+        if (PrevRange && CRLo <= HiVals[*PrevRange]) {
+          OverlapVal = HiVals[*PrevRange]; // Found overlap with range.
+          OverlapStmt = CaseRanges[*PrevRange].second;
         }
+        PrevRange = i;
 
         if (OverlapStmt) {
           // If we have a duplicate, report it.
@@ -1658,6 +1682,12 @@ Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 
Stmt *Switch,
         << CondExpr->getSourceRange();
     }
 
+    // Check the relocated case values with their local values from here.
+    if (!RelocatedCaseVals.empty()) {
+      llvm::append_range(CaseVals, RelocatedCaseVals);
+      llvm::stable_sort(CaseVals, CmpCaseVals);
+    }
+
     // Check to see if switch is over an Enum and handles all of its
     // values.  We only issue a warning if there is not 'default:', but
     // we still do the analysis to preserve this information in the AST
@@ -1696,6 +1726,9 @@ Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 
Stmt *Switch,
       EI = EnumVals.begin();
       for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
           RI != CaseRanges.end(); RI++) {
+        // A relocated range may overlap the previous one.
+        if (!RelocatedCaseRanges.empty())
+          EI = EnumVals.begin();
         Expr *CaseExpr = RI->second->getLHS();
         if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
                                               RI->first))

diff  --git a/clang/test/CodeGen/bpf-attr-preserve-access-index-enum-switch.c 
b/clang/test/CodeGen/bpf-attr-preserve-access-index-enum-switch.c
new file mode 100644
index 0000000000000..dee8fb337f097
--- /dev/null
+++ b/clang/test/CodeGen/bpf-attr-preserve-access-index-enum-switch.c
@@ -0,0 +1,276 @@
+// REQUIRES: bpf-registered-target
+// RUN: %clang_cc1 -triple bpf -emit-llvm -debug-info-kind=limited 
-disable-llvm-passes \
+// RUN:   %s -o - | FileCheck --check-prefixes=CHECK,LOCAL %s
+// RUN: %clang_cc1 -triple bpf -emit-llvm -disable-llvm-passes %s -o - \
+// RUN:   | FileCheck --check-prefixes=NODBG,LOCAL %s
+// RUN: %clang_cc1 -triple bpf -emit-llvm -debug-info-kind=limited 
-disable-llvm-passes \
+// RUN:   -fbpf-no-enum-reloc=e1,e2,e3 -DNO_ENUM_RELOC %s -o - \
+// RUN:   | FileCheck --check-prefix=CONST %s
+
+// A case value with an enumerator of a preserve_access_index enum is relocated
+// and compared before the switch. Without debug info, e.g., in a nodebug
+// function, its local value is compared before the switch. With
+// -fbpf-no-enum-reloc=, the case values are constants in the switch.
+
+#define __reloc__ __attribute__((preserve_access_index))
+
+enum e1 { E1_A = 1, E1_B = 4, E1_C = 8 } __reloc__;
+typedef enum : signed char { E2_A = 3 } __reloc__ e2;
+enum e3 : long { E3_A = 5 } __reloc__;
+
+void h(int);
+
+int test1(int x) {
+  switch (x) {
+  case 2:
+    return 1;
+  case E1_A:
+    return 2;
+  case E1_B ... E1_C:
+    return 3;
+  case E2_A + 100:
+    return 4;
+  case 10 ... E3_A + 10:
+    return 5;
+  default:
+    return 6;
+  }
+}
+
+// CHECK-LABEL: define dso_local i32 @test1
+// CHECK: [[X:%[0-9]+]] = load i32, ptr %x.addr
+// 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 ![[E1:[0-9]+]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i32
+// CHECK-NEXT: [[C:%[0-9]+]] = icmp eq i32 [[X]], [[T]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_A:[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 ![[E1]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i32
+// CHECK-NEXT: [[LO:%[0-9]+]] = icmp sge i32 [[X]], [[T]]
+// 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 ![[E1]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i32
+// CHECK-NEXT: [[HI:%[0-9]+]] = icmp sle i32 [[X]], [[T]]
+// CHECK-NEXT: [[C:%[0-9]+]] = and i1 [[LO]], [[HI]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_BC:[0-9a-z.]+]], label 
%[[D2:[0-9a-z.]+]]
+// CHECK: [[D2]]:
+// 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 ![[E2:[0-9]+]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i8
+// CHECK-NEXT: [[S:%[0-9a-z]+]] = sext i8 [[T]] to i32
+// CHECK-NEXT: [[ADD:%[0-9a-z]+]] = add nsw i32 [[S]], 100
+// CHECK-NEXT: [[C:%[0-9]+]] = icmp eq i32 [[X]], [[ADD]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_A2:[0-9a-z.]+]], label 
%[[D3:[0-9a-z.]+]]
+// CHECK: [[D3]]:
+// CHECK-NEXT: [[LO:%[0-9]+]] = icmp sge i32 [[X]], 10
+// 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 ![[E3:[0-9]+]]
+// CHECK-NEXT: [[ADD:%[0-9a-z]+]] = add nsw i64 [[V]], 10
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[ADD]] to i32
+// CHECK-NEXT: [[HI:%[0-9]+]] = icmp sle i32 [[X]], [[T]]
+// CHECK-NEXT: [[C:%[0-9]+]] = and i1 [[LO]], [[HI]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_R:[0-9a-z.]+]], label 
%[[D4:[0-9a-z.]+]]
+// CHECK: [[D4]]:
+// CHECK-NEXT: switch i32 [[X]], label %sw.default [
+// CHECK-NEXT: i32 2, label %sw.bb
+// CHECK-NEXT: ]
+// CHECK: [[BB_A]]:
+// CHECK-NEXT: store i32 2, ptr %retval
+// CHECK: [[BB_BC]]:
+// CHECK-NEXT: store i32 3, ptr %retval
+// CHECK: [[BB_A2]]:
+// CHECK-NEXT: store i32 4, ptr %retval
+// CHECK: [[BB_R]]:
+// CHECK-NEXT: store i32 5, ptr %retval
+
+// CONST-LABEL: define dso_local i32 @test1
+// CONST-NOT: @llvm.bpf.preserve.enum.value
+// CONST: switch i32 %{{[0-9]+}}, label %sw.default [
+// CONST-NEXT: i32 2, label %sw.bb
+// CONST-NEXT: i32 1, label %sw.bb1
+// CONST-NEXT: i32 4, label %sw.bb2
+// CONST-NEXT: i32 5, label %sw.bb2
+// CONST-NEXT: i32 6, label %sw.bb2
+// CONST-NEXT: i32 7, label %sw.bb2
+// CONST-NEXT: i32 8, label %sw.bb2
+// CONST-NEXT: i32 103, label %sw.bb3
+// CONST-NEXT: i32 10, label %sw.bb4
+// CONST-NEXT: i32 11, label %sw.bb4
+// CONST-NEXT: i32 12, label %sw.bb4
+// CONST-NEXT: i32 13, label %sw.bb4
+// CONST-NEXT: i32 14, label %sw.bb4
+// CONST-NEXT: i32 15, label %sw.bb4
+// CONST-NEXT: ]
+
+int test2(int x) {
+  switch (4) {
+  case E1_B:
+    switch (x) {
+    case E3_A:
+      h(1);
+    }
+    return 1;
+  case 6:
+    return 2;
+  }
+  return 0;
+}
+
+// CHECK-LABEL: define dso_local i32 @test2
+// CHECK: [[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 ![[E1]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i32
+// CHECK-NEXT: [[C:%[0-9]+]] = icmp eq i32 4, [[T]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_B:[0-9a-z.]+]], label 
%[[D1:[0-9a-z.]+]]
+// CHECK: [[D1]]:
+// CHECK-NEXT: switch i32 4, label %{{[0-9a-z.]+}} [
+// CHECK-NEXT: i32 6, label %{{[0-9a-z.]+}}
+// CHECK-NEXT: ]
+// CHECK: [[BB_B]]:
+// CHECK-NEXT: [[X:%[0-9]+]] = load i32, ptr %x.addr
+// 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 ![[E3]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i32
+// CHECK-NEXT: [[C:%[0-9]+]] = icmp eq i32 [[X]], [[T]]
+// CHECK-NEXT: br i1 [[C]], label %{{[0-9a-z.]+}}, label %[[D2:[0-9a-z.]+]]
+// CHECK: [[D2]]:
+// CHECK-NEXT: switch i32 [[X]], label %{{[0-9a-z.]+}} [
+// CHECK-NEXT: ]
+
+// CONST-LABEL: define dso_local i32 @test2
+// CONST-NOT: @llvm.bpf.preserve.enum.value
+// CONST: switch i32 %{{[0-9]+}}, label %sw.epilog [
+// CONST-NEXT: i32 5, label %sw.bb
+// CONST-NEXT: ]
+// CONST-NOT: switch
+// CONST: ret i32 1
+
+void test3(long x) {
+  switch (x) {
+  case 1:
+  case E2_A:
+  case 9:
+    h(x);
+  }
+}
+
+// CHECK-LABEL: define dso_local void @test3
+// CHECK: [[X:%[0-9]+]] = load i64, ptr %x.addr
+// 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 ![[E2]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i8
+// CHECK-NEXT: [[S:%[0-9]+]] = sext i8 [[T]] to i64
+// CHECK-NEXT: [[C:%[0-9]+]] = icmp eq i64 [[X]], [[S]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_C:[0-9a-z.]+]], label 
%[[D1:[0-9a-z.]+]]
+// CHECK: [[D1]]:
+// CHECK-NEXT: switch i64 [[X]], label %sw.epilog [
+// CHECK-NEXT: i64 1, label %[[BB_1:[0-9a-z.]+]]
+// CHECK-NEXT: i64 9, label %[[BB_9:[0-9a-z.]+]]
+// CHECK-NEXT: ]
+// CHECK: [[BB_1]]:
+// CHECK-NEXT: br label %[[BB_C]]
+// CHECK: [[BB_C]]:
+// CHECK-NEXT: br label %[[BB_9]]
+// CHECK: [[BB_9]]:
+// CHECK: call void @h
+
+// CONST-LABEL: define dso_local void @test3
+// CONST: switch i64 %{{[0-9]+}}, label %sw.epilog [
+// CONST-NEXT: i64 1, label %sw.bb
+// CONST-NEXT: i64 3, label %sw.bb
+// CONST-NEXT: i64 9, label %sw.bb
+// CONST-NEXT: ]
+
+__attribute__((nodebug)) int test4(int x) {
+  switch (x) {
+  case E1_A:
+    return 1;
+  }
+  return 0;
+}
+
+// LOCAL-LABEL: define dso_local i32 @test4
+// LOCAL-NOT: @llvm.bpf.preserve.enum.value
+// LOCAL: [[X:%[0-9]+]] = load i32, ptr %x.addr
+// LOCAL-NEXT: [[C:%[0-9]+]] = icmp eq i32 [[X]], 1
+// LOCAL-NEXT: br i1 [[C]], label %{{[0-9a-z.]+}}, label %[[D1:[0-9a-z.]+]]
+// LOCAL: [[D1]]:
+// LOCAL-NEXT: switch i32 [[X]], label %sw.epilog [
+// LOCAL-NEXT: ]
+
+#ifndef NO_ENUM_RELOC
+// A relocated case value is not checked for duplicates or overlaps, and is not
+// added to the switch. The first relocated case that matches, in source order,
+// is taken before the other cases.
+int test5(int x) {
+  switch (x) {
+  case E1_A:
+    return 1;
+  case 1:
+    return 2;
+  case E1_A:
+    return 3;
+  case E1_B ... E1_C:
+    return 4;
+  case 5:
+    return 5;
+  }
+  return 0;
+}
+#endif
+
+// CHECK-LABEL: define dso_local i32 @test5
+// CHECK: [[X:%[0-9]+]] = load i32, ptr %x.addr
+// 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 ![[E1]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i32
+// CHECK-NEXT: [[C:%[0-9]+]] = icmp eq i32 [[X]], [[T]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_A1:[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 ![[E1]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i32
+// CHECK-NEXT: [[C:%[0-9]+]] = icmp eq i32 [[X]], [[T]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_A2:[0-9a-z.]+]], label 
%[[D2:[0-9a-z.]+]]
+// CHECK: [[D2]]:
+// CHECK: [[C:%[0-9]+]] = and i1
+// CHECK-NEXT: br i1 [[C]], label %[[BB_BC:[0-9a-z.]+]], label 
%[[D3:[0-9a-z.]+]]
+// CHECK: [[D3]]:
+// CHECK-NEXT: switch i32 [[X]], label %sw.epilog [
+// CHECK-NEXT: i32 1, label %[[BB_1:[0-9a-z.]+]]
+// CHECK-NEXT: i32 5, label %[[BB_5:[0-9a-z.]+]]
+// CHECK-NEXT: ]
+// CHECK: [[BB_A1]]:
+// CHECK-NEXT: store i32 1, ptr %retval
+// CHECK: [[BB_1]]:
+// CHECK-NEXT: store i32 2, ptr %retval
+// CHECK: [[BB_A2]]:
+// CHECK-NEXT: store i32 3, ptr %retval
+// CHECK: [[BB_BC]]:
+// CHECK-NEXT: store i32 4, ptr %retval
+// CHECK: [[BB_5]]:
+// CHECK-NEXT: store i32 5, ptr %retval
+
+// NODBG-LABEL: define dso_local i32 @test5
+// NODBG: [[X:%[0-9]+]] = load i32, ptr %x.addr
+// NODBG-NEXT: [[C:%[0-9]+]] = icmp eq i32 [[X]], 1
+// NODBG-NEXT: br i1 [[C]], label %[[BB_A1:[0-9a-z.]+]], label 
%[[D1:[0-9a-z.]+]]
+// NODBG: [[D1]]:
+// NODBG-NEXT: [[C:%[0-9]+]] = icmp eq i32 [[X]], 1
+// NODBG-NEXT: br i1 [[C]], label %[[BB_A2:[0-9a-z.]+]], label 
%[[D2:[0-9a-z.]+]]
+// NODBG: [[D2]]:
+// NODBG-NEXT: [[LO:%[0-9]+]] = icmp sge i32 [[X]], 4
+// NODBG-NEXT: [[HI:%[0-9]+]] = icmp sle i32 [[X]], 8
+// NODBG-NEXT: [[C:%[0-9]+]] = and i1 [[LO]], [[HI]]
+// NODBG-NEXT: br i1 [[C]], label %[[BB_BC:[0-9a-z.]+]], label 
%[[D3:[0-9a-z.]+]]
+// NODBG: [[D3]]:
+// NODBG-NEXT: switch i32 [[X]], label %sw.epilog [
+// NODBG-NEXT: i32 1, label %[[BB_1:[0-9a-z.]+]]
+// NODBG-NEXT: i32 5, label %[[BB_5:[0-9a-z.]+]]
+// NODBG-NEXT: ]
+// NODBG: [[BB_A1]]:
+// NODBG-NEXT: store i32 1, ptr %retval
+// NODBG: [[BB_1]]:
+// NODBG-NEXT: store i32 2, ptr %retval
+// NODBG: [[BB_A2]]:
+// NODBG-NEXT: store i32 3, ptr %retval
+// NODBG: [[BB_BC]]:
+// NODBG-NEXT: store i32 4, ptr %retval
+// NODBG: [[BB_5]]:
+// NODBG-NEXT: store i32 5, ptr %retval
+
+// CHECK: ![[E1]] = !DICompositeType(tag: DW_TAG_enumeration_type, name: "e1"
+// CHECK: ![[E3]] = !DICompositeType(tag: DW_TAG_enumeration_type, name: "e3"
+// CHECK: ![[E2]] = !DIDerivedType(tag: DW_TAG_typedef, name: "e2"

diff  --git a/clang/test/Driver/bpf-no-enum-reloc.c 
b/clang/test/Driver/bpf-no-enum-reloc.c
new file mode 100644
index 0000000000000..53f42a8893b64
--- /dev/null
+++ b/clang/test/Driver/bpf-no-enum-reloc.c
@@ -0,0 +1,8 @@
+// RUN: %clang -### -c --target=bpf -fbpf-no-enum-reloc=e1,e2 \
+// RUN:   -fbpf-no-enum-reloc=e3 %s 2>&1 | FileCheck %s
+// CHECK: "-cc1"
+// CHECK-SAME: "-fbpf-no-enum-reloc=e1,e2" "-fbpf-no-enum-reloc=e3"
+
+// RUN: not %clang -### -c --target=x86_64 -fbpf-no-enum-reloc=e1 %s 2>&1 | \
+// RUN:   FileCheck --check-prefix=ERR %s
+// ERR: error: unsupported option '-fbpf-no-enum-reloc=' for target 'x86_64'

diff  --git a/clang/test/Sema/bpf-attr-preserve-access-index-enum-constant.c 
b/clang/test/Sema/bpf-attr-preserve-access-index-enum-constant.c
index a474160b7ffc3..d748660bf8d4f 100644
--- a/clang/test/Sema/bpf-attr-preserve-access-index-enum-constant.c
+++ b/clang/test/Sema/bpf-attr-preserve-access-index-enum-constant.c
@@ -4,11 +4,14 @@
 // RUN:   -Wno-error=bpf-enum-not-relocated %s
 // RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only 
-verify=none \
 // RUN:   -Wno-bpf-enum-not-relocated %s
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only 
-verify=none \
+// RUN:   -fbpf-no-enum-reloc=bpf_map_type,ops_flags %s
 
 // Where a constant is required, an enumerator of an enum with the
 // preserve_access_index attribute is not relocated, and its value is used.
 // This is diagnosed with -Wbpf-enum-not-relocated, an error by default, which
 // -Wno-error=, -Wno- or #pragma clang diagnostic opts out of.
+// -fbpf-no-enum-reloc= disables the relocation, so there is no diagnostic.
 
 // none-no-diagnostics
 

diff  --git a/clang/test/Sema/bpf-attr-preserve-access-index-enum-conversion.c 
b/clang/test/Sema/bpf-attr-preserve-access-index-enum-conversion.c
index dd070b5f6683f..bb0b1654a56a0 100644
--- a/clang/test/Sema/bpf-attr-preserve-access-index-enum-conversion.c
+++ b/clang/test/Sema/bpf-attr-preserve-access-index-enum-conversion.c
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only 
-Wconversion -verify %s
-// RUN: %clang_cc1 -triple bpf -fsyntax-only -Wconversion -verify %s
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only 
-Wconversion -Wtautological-value-range-compare -verify %s
+// RUN: %clang_cc1 -triple bpf -fsyntax-only -Wconversion 
-Wtautological-value-range-compare -verify %s
 
 // A relocated enumerator is converted from the unsigned long result of
 // __builtin_preserve_enum_value() to its own type, e.g., int. The user does 
not
@@ -18,3 +18,38 @@ int narrow(void) { int x = A; return x; }
 int narrow_builtin(void) {
   return __builtin_preserve_enum_value(*(enum E *)A, 1); // expected-warning 
{{implicit conversion loses integer precision: 'unsigned long' to 'int'}}
 }
+
+// A relocated enumerator is not a constant, but the range of its local value 
is
+// used, as without the attribute, so its conversion to another integer type 
and
+// its comparison with an unsigned value are not diagnosed if the local value
+// fits.
+enum F { D = 300 } __attribute__((preserve_access_index));
+
+unsigned to_unsigned(void) { unsigned u = A; return u; }
+unsigned char to_uchar(void) { return A; }
+unsigned char to_uchar_trunc(void) {
+  return D; // expected-warning {{implicit conversion loses integer precision: 
'int' to 'unsigned char'}}
+}
+int cmp_unsigned(unsigned x) { return x == A || x < A; }
+
+// The value of a relocated enumerator is only known at load time, so its
+// comparison with a constant is not tautological, even if the constant does
+// not fit in the bits of its local value.
+int cmp_const(void) { return A == 11 || 11 != A; }
+
+// A case value is converted to the promoted type of the switch condition.
+int case_unsigned(unsigned x, enum E e, unsigned char c) {
+  switch (x) {
+  case A:
+    return 1;
+  }
+  switch (e) {
+  case A:
+    return 2;
+  }
+  switch (c) {
+  case D: // expected-warning {{overflow converting case value to switch 
condition type (300 to 44)}}
+    return 3;
+  }
+  return 0;
+}

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
new file mode 100644
index 0000000000000..d8f0c9f64f3ab
--- /dev/null
+++ b/clang/test/Sema/bpf-attr-preserve-access-index-enum-switch.c
@@ -0,0 +1,70 @@
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only 
-verify=expected,reloc -Wswitch %s
+// RUN: %clang_cc1 -triple bpf -fsyntax-only -verify=expected,reloc -Wswitch %s
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only 
-verify=expected,noreloc -Wswitch \
+// 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,
+// 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));
+
+int f(int i, char c, enum E e) {
+  switch (i) {
+  case A: // noreloc-note {{previous case defined here}}
+    return 1;
+  case 1: // noreloc-error {{duplicate case value: 'A' and '1' both equal '1'}}
+    return 2;
+  case B: // noreloc-note {{previous case defined here}}
+    return 3;
+  case B + 1 ... C: // noreloc-error {{duplicate case value '6'}}
+    return 4;
+  case B: // noreloc-error {{duplicate case value 'B'}}
+    return 5;
+  case C + 1 ... B: // expected-warning {{empty case range specified}}
+    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}}
+    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;
+  }
+
+  // The cases without a relocated value are still checked.
+  switch (i) {
+  case 2: // expected-note {{previous case defined here}}
+  case B - 2: // noreloc-error {{duplicate case value '2'}} noreloc-note 
{{previous case defined here}}
+  case 2: // expected-error {{duplicate case value '2'}}
+  case 20 ... 22: // expected-error {{duplicate case value '21'}}
+  case 21: // expected-note {{previous case defined here}}
+    break;
+  }
+
+  switch (2) { // noreloc-warning {{no case matching constant switch condition 
'2'}}
+  case A:
+    break;
+  }
+
+  switch (e) { // expected-warning {{enumeration value 'D' not handled in 
switch}}
+  case A:
+  case 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}}
+  case 4 ... 10: // reloc-warning {{case value not in enumerated type 'enum 
E'}} noreloc-error {{duplicate case value '8'}}
+    break;
+  }
+
+  switch (c) {
+  case 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 8a129ea68cf2e..451f5e016289a 100644
--- a/clang/test/Sema/bpf-preserve-enum-value-parity.c
+++ b/clang/test/Sema/bpf-preserve-enum-value-parity.c
@@ -10,6 +10,8 @@
 // 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).
 #ifdef EXPLICIT
 enum E { A = 4 };
 #define X __builtin_preserve_enum_value(*(enum E *)A, 1)
@@ -40,9 +42,9 @@ 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}} attr-error {{enumerator 'A' is not relocated where a constant is 
required, although 'enum E' has the 'preserve_access_index' attribute}}
+  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}} attr-error {{enumerator 'A' is not relocated where a constant is 
required, although 'enum E' has the 'preserve_access_index' attribute}}
+  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}}


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

Reply via email to