xref: /llvm-project/llvm/lib/Analysis/DomConditionCache.cpp (revision d77067d08a3f56dc2d0e6c95bd2852c943df743a)
1 //===- DomConditionCache.cpp ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/Analysis/DomConditionCache.h"
10 #include "llvm/IR/PatternMatch.h"
11 
12 using namespace llvm;
13 using namespace llvm::PatternMatch;
14 
15 // TODO: This code is very similar to findAffectedValues() in
16 // AssumptionCache, but currently specialized to just the patterns that
17 // computeKnownBits() supports, and without the notion of result elem indices
18 // that are AC specific. Deduplicate this code once we have a clearer picture
19 // of how much they can be shared.
20 static void findAffectedValues(Value *Cond,
21                                SmallVectorImpl<Value *> &Affected) {
22   auto AddAffected = [&Affected](Value *V) {
23     if (isa<Argument>(V) || isa<GlobalValue>(V)) {
24       Affected.push_back(V);
25     } else if (auto *I = dyn_cast<Instruction>(V)) {
26       Affected.push_back(I);
27 
28       // Peek through unary operators to find the source of the condition.
29       Value *Op;
30       if (match(I, m_PtrToInt(m_Value(Op)))) {
31         if (isa<Instruction>(Op) || isa<Argument>(Op))
32           Affected.push_back(Op);
33       }
34     }
35   };
36 
37   ICmpInst::Predicate Pred;
38   Value *A;
39   Constant *C;
40   if (match(Cond, m_ICmp(Pred, m_Value(A), m_Constant(C)))) {
41     AddAffected(A);
42 
43     if (ICmpInst::isEquality(Pred)) {
44       Value *X;
45       // (X & C) or (X | C) or (X ^ C).
46       // (X << C) or (X >>_s C) or (X >>_u C).
47       if (match(A, m_BitwiseLogic(m_Value(X), m_ConstantInt())) ||
48           match(A, m_Shift(m_Value(X), m_ConstantInt())))
49         AddAffected(X);
50     } else {
51       Value *X;
52       // Handle (A + C1) u< C2, which is the canonical form of A > C3 && A < C4.
53       if (match(A, m_Add(m_Value(X), m_ConstantInt())))
54         AddAffected(X);
55     }
56   }
57 }
58 
59 void DomConditionCache::registerBranch(BranchInst *BI) {
60   assert(BI->isConditional() && "Must be conditional branch");
61   SmallVector<Value *, 16> Affected;
62   findAffectedValues(BI->getCondition(), Affected);
63   for (Value *V : Affected) {
64     auto &AV = AffectedValues[V];
65     if (!is_contained(AV, BI))
66       AV.push_back(BI);
67   }
68 }
69