llvmorg-github-actions[bot] wrote:

<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang-codegen

Author: yonghong-song

<details>
<summary>Changes</summary>

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 &gt;= BPF_FUNC_b &amp;&amp; id &lt;= 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 case values are constants in 
the switch, as before.

Sema checks a case label with the values in the local enum, so the existing 
checks, e.g., for duplicate case values, empty ranges, -Wswitch and overflow, 
are done as before. 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. The duplicate 
case value diagnostic still names the enumerator.

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=&lt;enum&gt;[,&lt;enum&gt;...] 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.

---

Patch is 35.99 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/243338.diff


15 Files Affected:

- (modified) clang/include/clang/Basic/AttrDocs.td (+14-5) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+7) 
- (modified) clang/include/clang/Basic/LangOptions.h (+4) 
- (modified) clang/include/clang/Options/Options.td (+7) 
- (modified) clang/include/clang/Sema/SemaBPF.h (+1) 
- (modified) clang/lib/CodeGen/CGStmt.cpp (+113-3) 
- (modified) clang/lib/CodeGen/CodeGenFunction.h (+2) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+5) 
- (modified) clang/lib/Sema/SemaBPF.cpp (+113-13) 
- (modified) clang/lib/Sema/SemaStmt.cpp (+9-1) 
- (added) clang/test/CodeGen/bpf-attr-preserve-access-index-enum-switch.c 
(+192) 
- (added) clang/test/Driver/bpf-no-enum-reloc.c (+8) 
- (modified) clang/test/Sema/bpf-attr-preserve-access-index-enum-constant.c 
(+3) 
- (added) clang/test/Sema/bpf-attr-preserve-access-index-enum-switch.c (+44) 
- (modified) clang/test/Sema/bpf-preserve-enum-value-parity.c (+4-2) 


``````````diff
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 9828968c9d0f4..f7df0069c1bf3 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -3087,11 +3087,20 @@ 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. The values in the local enum are
+used to check the case labels, e.g., for duplicates.
+
+`-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 dff45a081f2e8..9dc5cc7315c42 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -13648,6 +13648,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 9156640ff67c7..167737c43fe7c 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..517f42654f281 100644
--- a/clang/include/clang/Sema/SemaBPF.h
+++ b/clang/include/clang/Sema/SemaBPF.h
@@ -35,6 +35,7 @@ class SemaBPF : public SemaBase {
   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..8924e5c3b9b4c 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(), and debug info is available, return E without 
its
+/// ConstantExpr and casts.
+static const Expr *getBPFRelocatedCaseValue(CodeGenFunction &CGF,
+                                            const Expr *E) {
+  if (!E || !CGF.getTarget().getTriple().isBPF() ||
+      !CGF.CGM.getCodeGenOpts().hasReducedDebugInfo() || !CGF.getDebugInfo())
+    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 c73cae01f1508..c46c33a19cce2 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -3774,6 +3774,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 bd80f146f3a45..5d5e96b908b8e 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -1679,6 +1679,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..0e36531c84137 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)
@@ -360,6 +373,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 +389,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 +419,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 duplicates.
+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/SemaSt...
[truncated]

``````````

</details>


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

Reply via email to