SValBuilder.cpp revision 2a6e30d9ec947e26df55b4ea4eb5b583bb85ee96
1// SValBuilder.cpp - Basic class for all SValBuilder implementations -*- 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 SValBuilder, the base class for all (complete) SValBuilder
11//  implementations.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/AST/ExprCXX.h"
16#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
17#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h"
21
22using namespace clang;
23using namespace ento;
24
25//===----------------------------------------------------------------------===//
26// Basic SVal creation.
27//===----------------------------------------------------------------------===//
28
29void SValBuilder::anchor() { }
30
31DefinedOrUnknownSVal SValBuilder::makeZeroVal(QualType type) {
32  if (Loc::isLocType(type))
33    return makeNull();
34
35  if (type->isIntegerType())
36    return makeIntVal(0, type);
37
38  // FIXME: Handle floats.
39  // FIXME: Handle structs.
40  return UnknownVal();
41}
42
43NonLoc SValBuilder::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
44                                const llvm::APSInt& rhs, QualType type) {
45  // The Environment ensures we always get a persistent APSInt in
46  // BasicValueFactory, so we don't need to get the APSInt from
47  // BasicValueFactory again.
48  assert(lhs);
49  assert(!Loc::isLocType(type));
50  return nonloc::SymbolVal(SymMgr.getSymIntExpr(lhs, op, rhs, type));
51}
52
53NonLoc SValBuilder::makeNonLoc(const llvm::APSInt& lhs,
54                               BinaryOperator::Opcode op, const SymExpr *rhs,
55                               QualType type) {
56  assert(rhs);
57  assert(!Loc::isLocType(type));
58  return nonloc::SymbolVal(SymMgr.getIntSymExpr(lhs, op, rhs, type));
59}
60
61NonLoc SValBuilder::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
62                               const SymExpr *rhs, QualType type) {
63  assert(lhs && rhs);
64  assert(haveSameType(lhs->getType(Context), rhs->getType(Context)) == true);
65  assert(!Loc::isLocType(type));
66  return nonloc::SymbolVal(SymMgr.getSymSymExpr(lhs, op, rhs, type));
67}
68
69NonLoc SValBuilder::makeNonLoc(const SymExpr *operand,
70                               QualType fromTy, QualType toTy) {
71  assert(operand);
72  assert(!Loc::isLocType(toTy));
73  return nonloc::SymbolVal(SymMgr.getCastSymbol(operand, fromTy, toTy));
74}
75
76SVal SValBuilder::convertToArrayIndex(SVal val) {
77  if (val.isUnknownOrUndef())
78    return val;
79
80  // Common case: we have an appropriately sized integer.
81  if (nonloc::ConcreteInt* CI = dyn_cast<nonloc::ConcreteInt>(&val)) {
82    const llvm::APSInt& I = CI->getValue();
83    if (I.getBitWidth() == ArrayIndexWidth && I.isSigned())
84      return val;
85  }
86
87  return evalCastFromNonLoc(cast<NonLoc>(val), ArrayIndexTy);
88}
89
90nonloc::ConcreteInt SValBuilder::makeBoolVal(const CXXBoolLiteralExpr *boolean){
91  return makeTruthVal(boolean->getValue());
92}
93
94DefinedOrUnknownSVal
95SValBuilder::getRegionValueSymbolVal(const TypedValueRegion* region) {
96  QualType T = region->getValueType();
97
98  if (!SymbolManager::canSymbolicate(T))
99    return UnknownVal();
100
101  SymbolRef sym = SymMgr.getRegionValueSymbol(region);
102
103  if (Loc::isLocType(T))
104    return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
105
106  return nonloc::SymbolVal(sym);
107}
108
109DefinedOrUnknownSVal
110SValBuilder::getConjuredSymbolVal(const void *symbolTag,
111                                  const Expr *expr,
112                                  const LocationContext *LCtx,
113                                  unsigned count) {
114  QualType T = expr->getType();
115  return getConjuredSymbolVal(symbolTag, expr, LCtx, T, count);
116}
117
118DefinedOrUnknownSVal
119SValBuilder::getConjuredSymbolVal(const void *symbolTag,
120                                  const Expr *expr,
121                                  const LocationContext *LCtx,
122                                  QualType type,
123                                  unsigned count) {
124  if (!SymbolManager::canSymbolicate(type))
125    return UnknownVal();
126
127  SymbolRef sym = SymMgr.getConjuredSymbol(expr, LCtx, type, count, symbolTag);
128
129  if (Loc::isLocType(type))
130    return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
131
132  return nonloc::SymbolVal(sym);
133}
134
135
136DefinedOrUnknownSVal
137SValBuilder::getConjuredSymbolVal(const Stmt *stmt,
138                                  const LocationContext *LCtx,
139                                  QualType type,
140                                  unsigned visitCount) {
141  if (!SymbolManager::canSymbolicate(type))
142    return UnknownVal();
143
144  SymbolRef sym = SymMgr.getConjuredSymbol(stmt, LCtx, type, visitCount);
145
146  if (Loc::isLocType(type))
147    return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
148
149  return nonloc::SymbolVal(sym);
150}
151
152DefinedSVal SValBuilder::getMetadataSymbolVal(const void *symbolTag,
153                                              const MemRegion *region,
154                                              const Expr *expr, QualType type,
155                                              unsigned count) {
156  assert(SymbolManager::canSymbolicate(type) && "Invalid metadata symbol type");
157
158  SymbolRef sym =
159      SymMgr.getMetadataSymbol(region, expr, type, count, symbolTag);
160
161  if (Loc::isLocType(type))
162    return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
163
164  return nonloc::SymbolVal(sym);
165}
166
167DefinedOrUnknownSVal
168SValBuilder::getDerivedRegionValueSymbolVal(SymbolRef parentSymbol,
169                                             const TypedValueRegion *region) {
170  QualType T = region->getValueType();
171
172  if (!SymbolManager::canSymbolicate(T))
173    return UnknownVal();
174
175  SymbolRef sym = SymMgr.getDerivedSymbol(parentSymbol, region);
176
177  if (Loc::isLocType(T))
178    return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
179
180  return nonloc::SymbolVal(sym);
181}
182
183DefinedSVal SValBuilder::getFunctionPointer(const FunctionDecl *func) {
184  return loc::MemRegionVal(MemMgr.getFunctionTextRegion(func));
185}
186
187DefinedSVal SValBuilder::getBlockPointer(const BlockDecl *block,
188                                         CanQualType locTy,
189                                         const LocationContext *locContext) {
190  const BlockTextRegion *BC =
191    MemMgr.getBlockTextRegion(block, locTy, locContext->getAnalysisDeclContext());
192  const BlockDataRegion *BD = MemMgr.getBlockDataRegion(BC, locContext);
193  return loc::MemRegionVal(BD);
194}
195
196//===----------------------------------------------------------------------===//
197
198SVal SValBuilder::makeSymExprValNN(ProgramStateRef State,
199                                   BinaryOperator::Opcode Op,
200                                   NonLoc LHS, NonLoc RHS,
201                                   QualType ResultTy) {
202  const SymExpr *symLHS = LHS.getAsSymExpr();
203  const SymExpr *symRHS = RHS.getAsSymExpr();
204
205  if (symLHS && symRHS)
206    return makeNonLoc(symLHS, Op, symRHS, ResultTy);
207
208  if (symLHS)
209    if (const nonloc::ConcreteInt *rInt = dyn_cast<nonloc::ConcreteInt>(&RHS))
210      return makeNonLoc(symLHS, Op, rInt->getValue(), ResultTy);
211
212  if (symRHS)
213    if (const nonloc::ConcreteInt *lInt = dyn_cast<nonloc::ConcreteInt>(&LHS))
214      return makeNonLoc(lInt->getValue(), Op, symRHS, ResultTy);
215
216  return UnknownVal();
217}
218
219
220SVal SValBuilder::evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
221                            SVal lhs, SVal rhs, QualType type) {
222
223  if (lhs.isUndef() || rhs.isUndef())
224    return UndefinedVal();
225
226  if (lhs.isUnknown() || rhs.isUnknown())
227    return UnknownVal();
228
229  if (isa<Loc>(lhs)) {
230    if (isa<Loc>(rhs))
231      return evalBinOpLL(state, op, cast<Loc>(lhs), cast<Loc>(rhs), type);
232
233    return evalBinOpLN(state, op, cast<Loc>(lhs), cast<NonLoc>(rhs), type);
234  }
235
236  if (isa<Loc>(rhs)) {
237    // Support pointer arithmetic where the addend is on the left
238    // and the pointer on the right.
239    assert(op == BO_Add);
240
241    // Commute the operands.
242    return evalBinOpLN(state, op, cast<Loc>(rhs), cast<NonLoc>(lhs), type);
243  }
244
245  return evalBinOpNN(state, op, cast<NonLoc>(lhs), cast<NonLoc>(rhs), type);
246}
247
248DefinedOrUnknownSVal SValBuilder::evalEQ(ProgramStateRef state,
249                                         DefinedOrUnknownSVal lhs,
250                                         DefinedOrUnknownSVal rhs) {
251  return cast<DefinedOrUnknownSVal>(evalBinOp(state, BO_EQ, lhs, rhs,
252                                              Context.IntTy));
253}
254
255/// Recursively check if the pointer types are equal modulo const, volatile,
256/// and restrict qualifiers. Assumes the input types are canonical.
257/// TODO: This is based off of code in SemaCast; can we reuse it.
258static bool haveSimilarTypes(ASTContext &Context, QualType T1,
259                                                  QualType T2) {
260  while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
261    Qualifiers Quals1, Quals2;
262    T1 = Context.getUnqualifiedArrayType(T1, Quals1);
263    T2 = Context.getUnqualifiedArrayType(T2, Quals2);
264
265    // Make sure that non cvr-qualifiers the other qualifiers (e.g., address
266    // spaces) are identical.
267    Quals1.removeCVRQualifiers();
268    Quals2.removeCVRQualifiers();
269    if (Quals1 != Quals2)
270      return false;
271  }
272
273  if (T1 != T2)
274    return false;
275
276  return true;
277}
278
279// FIXME: should rewrite according to the cast kind.
280SVal SValBuilder::evalCast(SVal val, QualType castTy, QualType originalTy) {
281  castTy = Context.getCanonicalType(castTy);
282  originalTy = Context.getCanonicalType(originalTy);
283  if (val.isUnknownOrUndef() || castTy == originalTy)
284    return val;
285
286  // For const casts, just propagate the value.
287  if (!castTy->isVariableArrayType() && !originalTy->isVariableArrayType())
288    if (haveSimilarTypes(Context, Context.getPointerType(castTy),
289                                  Context.getPointerType(originalTy)))
290      return val;
291
292  // Check for casts from pointers to integers.
293  if (castTy->isIntegerType() && Loc::isLocType(originalTy))
294    return evalCastFromLoc(cast<Loc>(val), castTy);
295
296  // Check for casts from integers to pointers.
297  if (Loc::isLocType(castTy) && originalTy->isIntegerType()) {
298    if (nonloc::LocAsInteger *LV = dyn_cast<nonloc::LocAsInteger>(&val)) {
299      if (const MemRegion *R = LV->getLoc().getAsRegion()) {
300        StoreManager &storeMgr = StateMgr.getStoreManager();
301        R = storeMgr.castRegion(R, castTy);
302        return R ? SVal(loc::MemRegionVal(R)) : UnknownVal();
303      }
304      return LV->getLoc();
305    }
306    return dispatchCast(val, castTy);
307  }
308
309  // Just pass through function and block pointers.
310  if (originalTy->isBlockPointerType() || originalTy->isFunctionPointerType()) {
311    assert(Loc::isLocType(castTy));
312    return val;
313  }
314
315  // Check for casts from array type to another type.
316  if (originalTy->isArrayType()) {
317    // We will always decay to a pointer.
318    val = StateMgr.ArrayToPointer(cast<Loc>(val));
319
320    // Are we casting from an array to a pointer?  If so just pass on
321    // the decayed value.
322    if (castTy->isPointerType())
323      return val;
324
325    // Are we casting from an array to an integer?  If so, cast the decayed
326    // pointer value to an integer.
327    assert(castTy->isIntegerType());
328
329    // FIXME: Keep these here for now in case we decide soon that we
330    // need the original decayed type.
331    //    QualType elemTy = cast<ArrayType>(originalTy)->getElementType();
332    //    QualType pointerTy = C.getPointerType(elemTy);
333    return evalCastFromLoc(cast<Loc>(val), castTy);
334  }
335
336  // Check for casts from a region to a specific type.
337  if (const MemRegion *R = val.getAsRegion()) {
338    // Handle other casts of locations to integers.
339    if (castTy->isIntegerType())
340      return evalCastFromLoc(loc::MemRegionVal(R), castTy);
341
342    // FIXME: We should handle the case where we strip off view layers to get
343    //  to a desugared type.
344    if (!Loc::isLocType(castTy)) {
345      // FIXME: There can be gross cases where one casts the result of a function
346      // (that returns a pointer) to some other value that happens to fit
347      // within that pointer value.  We currently have no good way to
348      // model such operations.  When this happens, the underlying operation
349      // is that the caller is reasoning about bits.  Conceptually we are
350      // layering a "view" of a location on top of those bits.  Perhaps
351      // we need to be more lazy about mutual possible views, even on an
352      // SVal?  This may be necessary for bit-level reasoning as well.
353      return UnknownVal();
354    }
355
356    // We get a symbolic function pointer for a dereference of a function
357    // pointer, but it is of function type. Example:
358
359    //  struct FPRec {
360    //    void (*my_func)(int * x);
361    //  };
362    //
363    //  int bar(int x);
364    //
365    //  int f1_a(struct FPRec* foo) {
366    //    int x;
367    //    (*foo->my_func)(&x);
368    //    return bar(x)+1; // no-warning
369    //  }
370
371    assert(Loc::isLocType(originalTy) || originalTy->isFunctionType() ||
372           originalTy->isBlockPointerType() || castTy->isReferenceType());
373
374    StoreManager &storeMgr = StateMgr.getStoreManager();
375
376    // Delegate to store manager to get the result of casting a region to a
377    // different type.  If the MemRegion* returned is NULL, this expression
378    // Evaluates to UnknownVal.
379    R = storeMgr.castRegion(R, castTy);
380    return R ? SVal(loc::MemRegionVal(R)) : UnknownVal();
381  }
382
383  return dispatchCast(val, castTy);
384}
385