[clang] [llvm] [ValueTracking] Add dominating condition support in computeKnownBits() (PR #73662)

Yingwei Zheng via cfe-commits cfe-commits at lists.llvm.org
Tue Nov 28 18:19:43 PST 2023


================
@@ -0,0 +1,74 @@
+//===- DomConditionCache.cpp ----------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/Analysis/DomConditionCache.h"
+#include "llvm/IR/PatternMatch.h"
+
+using namespace llvm;
+using namespace llvm::PatternMatch;
+
+// TODO: This code is very similar to findAffectedValues() in
+// AssumptionCache, but currently specialized to just the patterns that
+// computeKnownBits() supports, and without the notion of result elem indices
+// that are AC specific. Deduplicate this code once we have a clearer picture
+// of how much they can be shared.
+static void findAffectedValues(Value *Cond,
+                               SmallVectorImpl<Value *> &Affected) {
+  auto AddAffected = [&Affected](Value *V) {
+    if (isa<Argument>(V) || isa<GlobalValue>(V)) {
+      Affected.push_back(V);
+    } else if (auto *I = dyn_cast<Instruction>(V)) {
+      Affected.push_back(I);
+
+      // Peek through unary operators to find the source of the condition.
+      Value *Op;
+      if (match(I, m_PtrToInt(m_Value(Op)))) {
+        if (isa<Instruction>(Op) || isa<Argument>(Op))
+          Affected.push_back(Op);
+      }
+    }
+  };
+
+  ICmpInst::Predicate Pred;
+  Value *A;
+  Constant *C;
+  if (match(Cond, m_ICmp(Pred, m_Value(A), m_Constant(C)))) {
+    AddAffected(A);
+
+    if (Pred == ICmpInst::ICMP_EQ) {
+      Value *X;
+      // (X & C) or (X | C) or (X ^ C).
+      // (X << C) or (X >>_s C) or (X >>_u C).
+      if (match(A, m_BitwiseLogic(m_Value(X), m_ConstantInt())) ||
+          match(A, m_Shift(m_Value(X), m_ConstantInt())))
+        AddAffected(X);
+    } else if (Pred == ICmpInst::ICMP_NE) {
+      Value *X;
+      // Handle (X & pow2 != 0).
+      if (match(A, m_And(m_Value(X), m_Power2())) && match(C, m_Zero()))
+        AddAffected(X);
+    } else if (Pred == ICmpInst::ICMP_ULT) {
----------------
dtcxzyw wrote:

```suggestion
    } else {
```
Does it also hold for other predicates?

https://github.com/llvm/llvm-project/blob/81e3e7e5d455f85e070a27763c578df493716ae9/llvm/lib/Analysis/ValueTracking.cpp#L701-L710


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


More information about the cfe-commits mailing list