1317019Sdim//== RangedConstraintManager.cpp --------------------------------*- C++ -*--==//
2317019Sdim//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6317019Sdim//
7317019Sdim//===----------------------------------------------------------------------===//
8317019Sdim//
9317019Sdim//  This file defines RangedConstraintManager, a class that provides a
10317019Sdim//  range-based constraint manager interface.
11317019Sdim//
12317019Sdim//===----------------------------------------------------------------------===//
13317019Sdim
14317019Sdim#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
15341825Sdim#include "clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h"
16317019Sdim
17317019Sdimnamespace clang {
18317019Sdim
19317019Sdimnamespace ento {
20317019Sdim
21317019SdimRangedConstraintManager::~RangedConstraintManager() {}
22317019Sdim
23317019SdimProgramStateRef RangedConstraintManager::assumeSym(ProgramStateRef State,
24317019Sdim                                                   SymbolRef Sym,
25317019Sdim                                                   bool Assumption) {
26317019Sdim  // Handle SymbolData.
27317019Sdim  if (isa<SymbolData>(Sym)) {
28317019Sdim    return assumeSymUnsupported(State, Sym, Assumption);
29317019Sdim
30317019Sdim    // Handle symbolic expression.
31317019Sdim  } else if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(Sym)) {
32317019Sdim    // We can only simplify expressions whose RHS is an integer.
33317019Sdim
34317019Sdim    BinaryOperator::Opcode op = SIE->getOpcode();
35327952Sdim    if (BinaryOperator::isComparisonOp(op) && op != BO_Cmp) {
36317019Sdim      if (!Assumption)
37317019Sdim        op = BinaryOperator::negateComparisonOp(op);
38317019Sdim
39317019Sdim      return assumeSymRel(State, SIE->getLHS(), op, SIE->getRHS());
40317019Sdim    }
41317019Sdim
42317019Sdim  } else if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(Sym)) {
43317019Sdim    // Translate "a != b" to "(b - a) != 0".
44317019Sdim    // We invert the order of the operands as a heuristic for how loop
45317019Sdim    // conditions are usually written ("begin != end") as compared to length
46317019Sdim    // calculations ("end - begin"). The more correct thing to do would be to
47317019Sdim    // canonicalize "a - b" and "b - a", which would allow us to treat
48317019Sdim    // "a != b" and "b != a" the same.
49317019Sdim    SymbolManager &SymMgr = getSymbolManager();
50317019Sdim    BinaryOperator::Opcode Op = SSE->getOpcode();
51317019Sdim    assert(BinaryOperator::isComparisonOp(Op));
52317019Sdim
53317019Sdim    // For now, we only support comparing pointers.
54341825Sdim    if (Loc::isLocType(SSE->getLHS()->getType()) &&
55341825Sdim        Loc::isLocType(SSE->getRHS()->getType())) {
56341825Sdim      QualType DiffTy = SymMgr.getContext().getPointerDiffType();
57341825Sdim      SymbolRef Subtraction =
58341825Sdim          SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub, SSE->getLHS(), DiffTy);
59317019Sdim
60341825Sdim      const llvm::APSInt &Zero = getBasicVals().getValue(0, DiffTy);
61341825Sdim      Op = BinaryOperator::reverseComparisonOp(Op);
62341825Sdim      if (!Assumption)
63341825Sdim        Op = BinaryOperator::negateComparisonOp(Op);
64341825Sdim      return assumeSymRel(State, Subtraction, Op, Zero);
65341825Sdim    }
66317019Sdim  }
67317019Sdim
68317019Sdim  // If we get here, there's nothing else we can do but treat the symbol as
69317019Sdim  // opaque.
70317019Sdim  return assumeSymUnsupported(State, Sym, Assumption);
71317019Sdim}
72317019Sdim
73317019SdimProgramStateRef RangedConstraintManager::assumeSymInclusiveRange(
74317019Sdim    ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
75317019Sdim    const llvm::APSInt &To, bool InRange) {
76317019Sdim  // Get the type used for calculating wraparound.
77317019Sdim  BasicValueFactory &BVF = getBasicVals();
78317019Sdim  APSIntType WraparoundType = BVF.getAPSIntType(Sym->getType());
79317019Sdim
80317019Sdim  llvm::APSInt Adjustment = WraparoundType.getZeroValue();
81317019Sdim  SymbolRef AdjustedSym = Sym;
82317019Sdim  computeAdjustment(AdjustedSym, Adjustment);
83317019Sdim
84317019Sdim  // Convert the right-hand side integer as necessary.
85317019Sdim  APSIntType ComparisonType = std::max(WraparoundType, APSIntType(From));
86317019Sdim  llvm::APSInt ConvertedFrom = ComparisonType.convert(From);
87317019Sdim  llvm::APSInt ConvertedTo = ComparisonType.convert(To);
88317019Sdim
89317019Sdim  // Prefer unsigned comparisons.
90317019Sdim  if (ComparisonType.getBitWidth() == WraparoundType.getBitWidth() &&
91317019Sdim      ComparisonType.isUnsigned() && !WraparoundType.isUnsigned())
92317019Sdim    Adjustment.setIsSigned(false);
93317019Sdim
94317019Sdim  if (InRange)
95317019Sdim    return assumeSymWithinInclusiveRange(State, AdjustedSym, ConvertedFrom,
96317019Sdim                                         ConvertedTo, Adjustment);
97317019Sdim  return assumeSymOutsideInclusiveRange(State, AdjustedSym, ConvertedFrom,
98317019Sdim                                        ConvertedTo, Adjustment);
99317019Sdim}
100317019Sdim
101317019SdimProgramStateRef
102317019SdimRangedConstraintManager::assumeSymUnsupported(ProgramStateRef State,
103317019Sdim                                              SymbolRef Sym, bool Assumption) {
104317019Sdim  BasicValueFactory &BVF = getBasicVals();
105317019Sdim  QualType T = Sym->getType();
106317019Sdim
107317019Sdim  // Non-integer types are not supported.
108317019Sdim  if (!T->isIntegralOrEnumerationType())
109317019Sdim    return State;
110317019Sdim
111317019Sdim  // Reverse the operation and add directly to state.
112317019Sdim  const llvm::APSInt &Zero = BVF.getValue(0, T);
113317019Sdim  if (Assumption)
114317019Sdim    return assumeSymNE(State, Sym, Zero, Zero);
115317019Sdim  else
116317019Sdim    return assumeSymEQ(State, Sym, Zero, Zero);
117317019Sdim}
118317019Sdim
119317019SdimProgramStateRef RangedConstraintManager::assumeSymRel(ProgramStateRef State,
120317019Sdim                                                      SymbolRef Sym,
121317019Sdim                                                      BinaryOperator::Opcode Op,
122317019Sdim                                                      const llvm::APSInt &Int) {
123317019Sdim  assert(BinaryOperator::isComparisonOp(Op) &&
124317019Sdim         "Non-comparison ops should be rewritten as comparisons to zero.");
125317019Sdim
126317019Sdim  // Simplification: translate an assume of a constraint of the form
127317019Sdim  // "(exp comparison_op expr) != 0" to true into an assume of
128317019Sdim  // "exp comparison_op expr" to true. (And similarly, an assume of the form
129317019Sdim  // "(exp comparison_op expr) == 0" to true into an assume of
130317019Sdim  // "exp comparison_op expr" to false.)
131317019Sdim  if (Int == 0 && (Op == BO_EQ || Op == BO_NE)) {
132317019Sdim    if (const BinarySymExpr *SE = dyn_cast<BinarySymExpr>(Sym))
133317019Sdim      if (BinaryOperator::isComparisonOp(SE->getOpcode()))
134317019Sdim        return assumeSym(State, Sym, (Op == BO_NE ? true : false));
135317019Sdim  }
136317019Sdim
137317019Sdim  // Get the type used for calculating wraparound.
138317019Sdim  BasicValueFactory &BVF = getBasicVals();
139317019Sdim  APSIntType WraparoundType = BVF.getAPSIntType(Sym->getType());
140317019Sdim
141317019Sdim  // We only handle simple comparisons of the form "$sym == constant"
142317019Sdim  // or "($sym+constant1) == constant2".
143317019Sdim  // The adjustment is "constant1" in the above expression. It's used to
144317019Sdim  // "slide" the solution range around for modular arithmetic. For example,
145317019Sdim  // x < 4 has the solution [0, 3]. x+2 < 4 has the solution [0-2, 3-2], which
146317019Sdim  // in modular arithmetic is [0, 1] U [UINT_MAX-1, UINT_MAX]. It's up to
147317019Sdim  // the subclasses of SimpleConstraintManager to handle the adjustment.
148317019Sdim  llvm::APSInt Adjustment = WraparoundType.getZeroValue();
149317019Sdim  computeAdjustment(Sym, Adjustment);
150317019Sdim
151317019Sdim  // Convert the right-hand side integer as necessary.
152317019Sdim  APSIntType ComparisonType = std::max(WraparoundType, APSIntType(Int));
153317019Sdim  llvm::APSInt ConvertedInt = ComparisonType.convert(Int);
154317019Sdim
155317019Sdim  // Prefer unsigned comparisons.
156317019Sdim  if (ComparisonType.getBitWidth() == WraparoundType.getBitWidth() &&
157317019Sdim      ComparisonType.isUnsigned() && !WraparoundType.isUnsigned())
158317019Sdim    Adjustment.setIsSigned(false);
159317019Sdim
160317019Sdim  switch (Op) {
161317019Sdim  default:
162317019Sdim    llvm_unreachable("invalid operation not caught by assertion above");
163317019Sdim
164317019Sdim  case BO_EQ:
165317019Sdim    return assumeSymEQ(State, Sym, ConvertedInt, Adjustment);
166317019Sdim
167317019Sdim  case BO_NE:
168317019Sdim    return assumeSymNE(State, Sym, ConvertedInt, Adjustment);
169317019Sdim
170317019Sdim  case BO_GT:
171317019Sdim    return assumeSymGT(State, Sym, ConvertedInt, Adjustment);
172317019Sdim
173317019Sdim  case BO_GE:
174317019Sdim    return assumeSymGE(State, Sym, ConvertedInt, Adjustment);
175317019Sdim
176317019Sdim  case BO_LT:
177317019Sdim    return assumeSymLT(State, Sym, ConvertedInt, Adjustment);
178317019Sdim
179317019Sdim  case BO_LE:
180317019Sdim    return assumeSymLE(State, Sym, ConvertedInt, Adjustment);
181317019Sdim  } // end switch
182317019Sdim}
183317019Sdim
184317019Sdimvoid RangedConstraintManager::computeAdjustment(SymbolRef &Sym,
185317019Sdim                                                llvm::APSInt &Adjustment) {
186317019Sdim  // Is it a "($sym+constant1)" expression?
187317019Sdim  if (const SymIntExpr *SE = dyn_cast<SymIntExpr>(Sym)) {
188317019Sdim    BinaryOperator::Opcode Op = SE->getOpcode();
189317019Sdim    if (Op == BO_Add || Op == BO_Sub) {
190317019Sdim      Sym = SE->getLHS();
191317019Sdim      Adjustment = APSIntType(Adjustment).convert(SE->getRHS());
192317019Sdim
193317019Sdim      // Don't forget to negate the adjustment if it's being subtracted.
194317019Sdim      // This should happen /after/ promotion, in case the value being
195317019Sdim      // subtracted is, say, CHAR_MIN, and the promoted type is 'int'.
196317019Sdim      if (Op == BO_Sub)
197317019Sdim        Adjustment = -Adjustment;
198317019Sdim    }
199317019Sdim  }
200317019Sdim}
201317019Sdim
202344779Sdimvoid *ProgramStateTrait<ConstraintRange>::GDMIndex() {
203344779Sdim  static int Index;
204344779Sdim  return &Index;
205344779Sdim}
206344779Sdim
207317019Sdim} // end of namespace ento
208317019Sdim
209317019Sdim} // end of namespace clang
210