xref: /llvm-project/clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp (revision 61e221f68de5b7b32cea552e3b4ef7838eb2182c)
1 //== SimpleConstraintManager.cpp --------------------------------*- C++ -*--==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines SimpleConstraintManager, a class that holds code shared
11 //  between BasicConstraintManager and RangeConstraintManager.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "SimpleConstraintManager.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
19 
20 namespace clang {
21 
22 namespace ento {
23 
24 SimpleConstraintManager::~SimpleConstraintManager() {}
25 
26 bool SimpleConstraintManager::canReasonAbout(SVal X) const {
27   Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
28   if (SymVal && SymVal->isExpression()) {
29     const SymExpr *SE = SymVal->getSymbol();
30 
31     if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SE)) {
32       switch (SIE->getOpcode()) {
33           // We don't reason yet about bitwise-constraints on symbolic values.
34         case BO_And:
35         case BO_Or:
36         case BO_Xor:
37           return false;
38         // We don't reason yet about these arithmetic constraints on
39         // symbolic values.
40         case BO_Mul:
41         case BO_Div:
42         case BO_Rem:
43         case BO_Shl:
44         case BO_Shr:
45           return false;
46         // All other cases.
47         default:
48           return true;
49       }
50     }
51 
52     if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(SE)) {
53       if (BinaryOperator::isComparisonOp(SSE->getOpcode())) {
54         // We handle Loc <> Loc comparisons, but not (yet) NonLoc <> NonLoc.
55         if (Loc::isLocType(SSE->getLHS()->getType())) {
56           assert(Loc::isLocType(SSE->getRHS()->getType()));
57           return true;
58         }
59       }
60     }
61 
62     return false;
63   }
64 
65   return true;
66 }
67 
68 ProgramStateRef SimpleConstraintManager::assume(ProgramStateRef state,
69                                                DefinedSVal Cond,
70                                                bool Assumption) {
71   if (Optional<NonLoc> NV = Cond.getAs<NonLoc>())
72     return assume(state, *NV, Assumption);
73   return assume(state, Cond.castAs<Loc>(), Assumption);
74 }
75 
76 ProgramStateRef SimpleConstraintManager::assume(ProgramStateRef state, Loc cond,
77                                                bool assumption) {
78   state = assumeAux(state, cond, assumption);
79   if (NotifyAssumeClients && SU)
80     return SU->processAssume(state, cond, assumption);
81   return state;
82 }
83 
84 ProgramStateRef SimpleConstraintManager::assumeAux(ProgramStateRef state,
85                                                   Loc Cond, bool Assumption) {
86   switch (Cond.getSubKind()) {
87   default:
88     assert (false && "'Assume' not implemented for this Loc.");
89     return state;
90 
91   case loc::MemRegionKind: {
92     // FIXME: Should this go into the storemanager?
93 
94     const MemRegion *R = Cond.castAs<loc::MemRegionVal>().getRegion();
95     const SubRegion *SubR = dyn_cast<SubRegion>(R);
96 
97     while (SubR) {
98       // FIXME: now we only find the first symbolic region.
99       if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(SubR)) {
100         const llvm::APSInt &zero = getBasicVals().getZeroWithPtrWidth();
101         if (Assumption)
102           return assumeSymNE(state, SymR->getSymbol(), zero, zero);
103         else
104           return assumeSymEQ(state, SymR->getSymbol(), zero, zero);
105       }
106       SubR = dyn_cast<SubRegion>(SubR->getSuperRegion());
107     }
108 
109     // FALL-THROUGH.
110   }
111 
112   case loc::GotoLabelKind:
113     return Assumption ? state : NULL;
114 
115   case loc::ConcreteIntKind: {
116     bool b = Cond.castAs<loc::ConcreteInt>().getValue() != 0;
117     bool isFeasible = b ? Assumption : !Assumption;
118     return isFeasible ? state : NULL;
119   }
120   } // end switch
121 }
122 
123 ProgramStateRef SimpleConstraintManager::assume(ProgramStateRef state,
124                                                NonLoc cond,
125                                                bool assumption) {
126   state = assumeAux(state, cond, assumption);
127   if (NotifyAssumeClients && SU)
128     return SU->processAssume(state, cond, assumption);
129   return state;
130 }
131 
132 
133 ProgramStateRef
134 SimpleConstraintManager::assumeAuxForSymbol(ProgramStateRef State,
135                                             SymbolRef Sym, bool Assumption) {
136   BasicValueFactory &BVF = getBasicVals();
137   QualType T = Sym->getType();
138 
139   // None of the constraint solvers currently support non-integer types.
140   if (!T->isIntegralOrEnumerationType())
141     return State;
142 
143   const llvm::APSInt &zero = BVF.getValue(0, T);
144   if (Assumption)
145     return assumeSymNE(State, Sym, zero, zero);
146   else
147     return assumeSymEQ(State, Sym, zero, zero);
148 }
149 
150 ProgramStateRef SimpleConstraintManager::assumeAux(ProgramStateRef state,
151                                                   NonLoc Cond,
152                                                   bool Assumption) {
153 
154   // We cannot reason about SymSymExprs, and can only reason about some
155   // SymIntExprs.
156   if (!canReasonAbout(Cond)) {
157     // Just add the constraint to the expression without trying to simplify.
158     SymbolRef sym = Cond.getAsSymExpr();
159     return assumeAuxForSymbol(state, sym, Assumption);
160   }
161 
162   switch (Cond.getSubKind()) {
163   default:
164     llvm_unreachable("'Assume' not implemented for this NonLoc");
165 
166   case nonloc::SymbolValKind: {
167     nonloc::SymbolVal SV = Cond.castAs<nonloc::SymbolVal>();
168     SymbolRef sym = SV.getSymbol();
169     assert(sym);
170 
171     // Handle SymbolData.
172     if (!SV.isExpression()) {
173       return assumeAuxForSymbol(state, sym, Assumption);
174 
175     // Handle symbolic expression.
176     } else if (const SymIntExpr *SE = dyn_cast<SymIntExpr>(sym)) {
177       // We can only simplify expressions whose RHS is an integer.
178 
179       BinaryOperator::Opcode op = SE->getOpcode();
180       if (BinaryOperator::isComparisonOp(op)) {
181         if (!Assumption)
182           op = BinaryOperator::negateComparisonOp(op);
183 
184         return assumeSymRel(state, SE->getLHS(), op, SE->getRHS());
185       }
186 
187     } else if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(sym)) {
188       // Translate "a != b" to "(b - a) != 0".
189       // We invert the order of the operands as a heuristic for how loop
190       // conditions are usually written ("begin != end") as compared to length
191       // calculations ("end - begin"). The more correct thing to do would be to
192       // canonicalize "a - b" and "b - a", which would allow us to treat
193       // "a != b" and "b != a" the same.
194       SymbolManager &SymMgr = getSymbolManager();
195       BinaryOperator::Opcode Op = SSE->getOpcode();
196       assert(BinaryOperator::isComparisonOp(Op));
197 
198       // For now, we only support comparing pointers.
199       assert(Loc::isLocType(SSE->getLHS()->getType()));
200       assert(Loc::isLocType(SSE->getRHS()->getType()));
201       QualType DiffTy = SymMgr.getContext().getPointerDiffType();
202       SymbolRef Subtraction = SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub,
203                                                    SSE->getLHS(), DiffTy);
204 
205       const llvm::APSInt &Zero = getBasicVals().getValue(0, DiffTy);
206       Op = BinaryOperator::reverseComparisonOp(Op);
207       if (!Assumption)
208         Op = BinaryOperator::negateComparisonOp(Op);
209       return assumeSymRel(state, Subtraction, Op, Zero);
210     }
211 
212     // If we get here, there's nothing else we can do but treat the symbol as
213     // opaque.
214     return assumeAuxForSymbol(state, sym, Assumption);
215   }
216 
217   case nonloc::ConcreteIntKind: {
218     bool b = Cond.castAs<nonloc::ConcreteInt>().getValue() != 0;
219     bool isFeasible = b ? Assumption : !Assumption;
220     return isFeasible ? state : NULL;
221   }
222 
223   case nonloc::LocAsIntegerKind:
224     return assumeAux(state, Cond.castAs<nonloc::LocAsInteger>().getLoc(),
225                      Assumption);
226   } // end switch
227 }
228 
229 static void computeAdjustment(SymbolRef &Sym, llvm::APSInt &Adjustment) {
230   // Is it a "($sym+constant1)" expression?
231   if (const SymIntExpr *SE = dyn_cast<SymIntExpr>(Sym)) {
232     BinaryOperator::Opcode Op = SE->getOpcode();
233     if (Op == BO_Add || Op == BO_Sub) {
234       Sym = SE->getLHS();
235       Adjustment = APSIntType(Adjustment).convert(SE->getRHS());
236 
237       // Don't forget to negate the adjustment if it's being subtracted.
238       // This should happen /after/ promotion, in case the value being
239       // subtracted is, say, CHAR_MIN, and the promoted type is 'int'.
240       if (Op == BO_Sub)
241         Adjustment = -Adjustment;
242     }
243   }
244 }
245 
246 ProgramStateRef SimpleConstraintManager::assumeSymRel(ProgramStateRef state,
247                                                      const SymExpr *LHS,
248                                                      BinaryOperator::Opcode op,
249                                                      const llvm::APSInt& Int) {
250   assert(BinaryOperator::isComparisonOp(op) &&
251          "Non-comparison ops should be rewritten as comparisons to zero.");
252 
253   // Get the type used for calculating wraparound.
254   BasicValueFactory &BVF = getBasicVals();
255   APSIntType WraparoundType = BVF.getAPSIntType(LHS->getType());
256 
257   // We only handle simple comparisons of the form "$sym == constant"
258   // or "($sym+constant1) == constant2".
259   // The adjustment is "constant1" in the above expression. It's used to
260   // "slide" the solution range around for modular arithmetic. For example,
261   // x < 4 has the solution [0, 3]. x+2 < 4 has the solution [0-2, 3-2], which
262   // in modular arithmetic is [0, 1] U [UINT_MAX-1, UINT_MAX]. It's up to
263   // the subclasses of SimpleConstraintManager to handle the adjustment.
264   SymbolRef Sym = LHS;
265   llvm::APSInt Adjustment = WraparoundType.getZeroValue();
266   computeAdjustment(Sym, Adjustment);
267 
268   // Convert the right-hand side integer as necessary.
269   APSIntType ComparisonType = std::max(WraparoundType, APSIntType(Int));
270   llvm::APSInt ConvertedInt = ComparisonType.convert(Int);
271 
272   // Prefer unsigned comparisons.
273   if (ComparisonType.getBitWidth() == WraparoundType.getBitWidth() &&
274       ComparisonType.isUnsigned() && !WraparoundType.isUnsigned())
275     Adjustment.setIsSigned(false);
276 
277   switch (op) {
278   default:
279     llvm_unreachable("invalid operation not caught by assertion above");
280 
281   case BO_EQ:
282     return assumeSymEQ(state, Sym, ConvertedInt, Adjustment);
283 
284   case BO_NE:
285     return assumeSymNE(state, Sym, ConvertedInt, Adjustment);
286 
287   case BO_GT:
288     return assumeSymGT(state, Sym, ConvertedInt, Adjustment);
289 
290   case BO_GE:
291     return assumeSymGE(state, Sym, ConvertedInt, Adjustment);
292 
293   case BO_LT:
294     return assumeSymLT(state, Sym, ConvertedInt, Adjustment);
295 
296   case BO_LE:
297     return assumeSymLE(state, Sym, ConvertedInt, Adjustment);
298   } // end switch
299 }
300 
301 } // end of namespace ento
302 
303 } // end of namespace clang
304