summaryrefslogtreecommitdiffstats
path: root/lib/Analysis/SimpleSValuator.cpp
blob: 9850b2e036821e897d8c96b5a0fe7ea970e1eca4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
// SimpleSValuator.cpp - A basic SValuator ------------------------*- C++ -*--//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file defines SimpleSValuator, a basic implementation of SValuator.
//
//===----------------------------------------------------------------------===//

#include "clang/Analysis/PathSensitive/SValuator.h"
#include "clang/Analysis/PathSensitive/GRState.h"
#include "llvm/Support/Compiler.h"

using namespace clang;

namespace {
class VISIBILITY_HIDDEN SimpleSValuator : public SValuator {
protected:
  virtual SVal EvalCastNL(NonLoc val, QualType castTy);    
  virtual SVal EvalCastL(Loc val, QualType castTy);    

public:
  SimpleSValuator(ValueManager &valMgr) : SValuator(valMgr) {}
  virtual ~SimpleSValuator() {}
  
  virtual SVal EvalMinus(NonLoc val);    
  virtual SVal EvalComplement(NonLoc val);    
  virtual SVal EvalBinOpNN(BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs,
                           QualType resultTy);
  virtual SVal EvalBinOpLL(BinaryOperator::Opcode op, Loc lhs, Loc rhs,
                           QualType resultTy);
  virtual SVal EvalBinOpLN(const GRState *state, BinaryOperator::Opcode op,
                           Loc lhs, NonLoc rhs, QualType resultTy);
}; 
} // end anonymous namespace

SValuator *clang::CreateSimpleSValuator(ValueManager &valMgr) {
  return new SimpleSValuator(valMgr);
}

//===----------------------------------------------------------------------===//
// Transfer function for Casts.
//===----------------------------------------------------------------------===//

SVal SimpleSValuator::EvalCastNL(NonLoc val, QualType castTy) {
  
  bool isLocType = Loc::IsLocType(castTy);
  
  if (nonloc::LocAsInteger *LI = dyn_cast<nonloc::LocAsInteger>(&val)) {
    if (isLocType)
      return LI->getLoc();
    
    ASTContext &Ctx = ValMgr.getContext();    
    
    // FIXME: Support promotions/truncations.
    if (Ctx.getTypeSize(castTy) == Ctx.getTypeSize(Ctx.VoidPtrTy))
      return val;
    
    return UnknownVal();
  }

  if (const SymExpr *se = val.getAsSymbolicExpression()) {
    ASTContext &Ctx = ValMgr.getContext();
    QualType T = Ctx.getCanonicalType(se->getType(Ctx));
    if (T == Ctx.getCanonicalType(castTy))
      return val;
    
    return UnknownVal();
  }
  
  if (!isa<nonloc::ConcreteInt>(val))
    return UnknownVal();
  
  // Only handle casts from integers to integers.
  if (!isLocType && !castTy->isIntegerType())
    return UnknownVal();
  
  llvm::APSInt i = cast<nonloc::ConcreteInt>(val).getValue();
  i.setIsUnsigned(castTy->isUnsignedIntegerType() || Loc::IsLocType(castTy));
  i.extOrTrunc(ValMgr.getContext().getTypeSize(castTy));

  if (isLocType)
    return ValMgr.makeIntLocVal(i);
  else
    return ValMgr.makeIntVal(i);
}

SVal SimpleSValuator::EvalCastL(Loc val, QualType castTy) {
  
  // Casts from pointers -> pointers, just return the lval.
  //
  // Casts from pointers -> references, just return the lval.  These
  //   can be introduced by the frontend for corner cases, e.g
  //   casting from va_list* to __builtin_va_list&.
  //
  assert(!val.isUnknownOrUndef());
  
  if (Loc::IsLocType(castTy) || castTy->isReferenceType())
    return val;
  
  // FIXME: Handle transparent unions where a value can be "transparently"
  //  lifted into a union type.
  if (castTy->isUnionType())
    return UnknownVal();
  
  assert(castTy->isIntegerType());
  unsigned BitWidth = ValMgr.getContext().getTypeSize(castTy);

  if (!isa<loc::ConcreteInt>(val))
    return ValMgr.makeLocAsInteger(val, BitWidth);
  
  llvm::APSInt i = cast<loc::ConcreteInt>(val).getValue();
  i.setIsUnsigned(castTy->isUnsignedIntegerType() || Loc::IsLocType(castTy));
  i.extOrTrunc(BitWidth);
  return ValMgr.makeIntVal(i);
}

//===----------------------------------------------------------------------===//
// Transfer function for unary operators.
//===----------------------------------------------------------------------===//

SVal SimpleSValuator::EvalMinus(NonLoc val) {
  switch (val.getSubKind()) {      
  case nonloc::ConcreteIntKind:
    return cast<nonloc::ConcreteInt>(val).evalMinus(ValMgr);
  default:
    return UnknownVal();
  }
}

SVal SimpleSValuator::EvalComplement(NonLoc X) {
  switch (X.getSubKind()) {
  case nonloc::ConcreteIntKind:
    return cast<nonloc::ConcreteInt>(X).evalComplement(ValMgr);
  default:
    return UnknownVal();
  }
}

//===----------------------------------------------------------------------===//
// Transfer function for binary operators.
//===----------------------------------------------------------------------===//

static BinaryOperator::Opcode NegateComparison(BinaryOperator::Opcode op) {
  switch (op) {
  default:
    assert(false && "Invalid opcode.");
  case BinaryOperator::LT: return BinaryOperator::GE;
  case BinaryOperator::GT: return BinaryOperator::LE;
  case BinaryOperator::LE: return BinaryOperator::GT;
  case BinaryOperator::GE: return BinaryOperator::LT;
  case BinaryOperator::EQ: return BinaryOperator::NE;
  case BinaryOperator::NE: return BinaryOperator::EQ;
  }
}

// Equality operators for Locs.  
// FIXME: All this logic will be revamped when we have MemRegion::getLocation()
// implemented.

static SVal EvalEquality(ValueManager &ValMgr, Loc lhs, Loc rhs, bool isEqual,
                         QualType resultTy) {
  
  switch (lhs.getSubKind()) {
    default:
      assert(false && "EQ/NE not implemented for this Loc.");
      return UnknownVal();
      
    case loc::ConcreteIntKind: {
      if (SymbolRef rSym = rhs.getAsSymbol())
        return ValMgr.makeNonLoc(rSym,
                                 isEqual ? BinaryOperator::EQ
                                 : BinaryOperator::NE,
                                 cast<loc::ConcreteInt>(lhs).getValue(),
                                 resultTy);
      break;
    }    
    case loc::MemRegionKind: {
      if (SymbolRef lSym = lhs.getAsLocSymbol()) {
        if (isa<loc::ConcreteInt>(rhs)) {
          return ValMgr.makeNonLoc(lSym,
                                   isEqual ? BinaryOperator::EQ
                                   : BinaryOperator::NE,
                                   cast<loc::ConcreteInt>(rhs).getValue(),
                                   resultTy);
        }
      }
      break;
    }
      
    case loc::GotoLabelKind:
      break;
  }
  
  return ValMgr.makeTruthVal(isEqual ? lhs == rhs : lhs != rhs, resultTy);
}

SVal SimpleSValuator::EvalBinOpNN(BinaryOperator::Opcode op,
                                  NonLoc lhs, NonLoc rhs,
                                  QualType resultTy)  {

  assert(!lhs.isUnknownOrUndef());
  assert(!rhs.isUnknownOrUndef());

  // Handle trivial case where left-side and right-side are the same.
  if (lhs == rhs)
    switch (op) {
      default:
        break;
      case BinaryOperator::EQ:
      case BinaryOperator::LE:
      case BinaryOperator::GE:
        return ValMgr.makeTruthVal(true, resultTy);
      case BinaryOperator::LT:
      case BinaryOperator::GT:
      case BinaryOperator::NE:
        return ValMgr.makeTruthVal(false, resultTy);
    }
  
  while (1) {
    switch (lhs.getSubKind()) {
    default:
      return UnknownVal();        
    case nonloc::LocAsIntegerKind: {
      Loc lhsL = cast<nonloc::LocAsInteger>(lhs).getLoc();        
      switch (rhs.getSubKind()) {
        case nonloc::LocAsIntegerKind:
          return EvalBinOpLL(op, lhsL, cast<nonloc::LocAsInteger>(rhs).getLoc(),
                             resultTy); 
        case nonloc::ConcreteIntKind: {
          // Transform the integer into a location and compare.
          ASTContext& Ctx = ValMgr.getContext();
          llvm::APSInt i = cast<nonloc::ConcreteInt>(rhs).getValue();
          i.setIsUnsigned(true);
          i.extOrTrunc(Ctx.getTypeSize(Ctx.VoidPtrTy));
          return EvalBinOpLL(op, lhsL, ValMgr.makeLoc(i), resultTy);
        }
        default: 
          switch (op) {
            case BinaryOperator::EQ:
              return ValMgr.makeTruthVal(false, resultTy);
            case BinaryOperator::NE:
              return ValMgr.makeTruthVal(true, resultTy);
            default:
              // This case also handles pointer arithmetic.
              return UnknownVal();
          }
      }
    }      
    case nonloc::SymExprValKind: {
      // Logical not?        
      if (!(op == BinaryOperator::EQ && rhs.isZeroConstant()))
        return UnknownVal();

      const SymExpr *symExpr =
        cast<nonloc::SymExprVal>(lhs).getSymbolicExpression();
      
      // Only handle ($sym op constant) for now.
      if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(symExpr)) {
        BinaryOperator::Opcode opc = symIntExpr->getOpcode();
        switch (opc) {
          case BinaryOperator::LAnd:
          case BinaryOperator::LOr:
            assert(false && "Logical operators handled by branching logic.");
            return UnknownVal();
          case BinaryOperator::Assign:
          case BinaryOperator::MulAssign:
          case BinaryOperator::DivAssign:
          case BinaryOperator::RemAssign:
          case BinaryOperator::AddAssign:
          case BinaryOperator::SubAssign:
          case BinaryOperator::ShlAssign:
          case BinaryOperator::ShrAssign:
          case BinaryOperator::AndAssign:
          case BinaryOperator::XorAssign:
          case BinaryOperator::OrAssign:
          case BinaryOperator::Comma:
            assert(false && "'=' and ',' operators handled by GRExprEngine.");
            return UnknownVal();
          case BinaryOperator::PtrMemD:
          case BinaryOperator::PtrMemI:
            assert(false && "Pointer arithmetic not handled here.");
            return UnknownVal();
          case BinaryOperator::Mul:
          case BinaryOperator::Div:
          case BinaryOperator::Rem:
          case BinaryOperator::Add:
          case BinaryOperator::Sub:
          case BinaryOperator::Shl:
          case BinaryOperator::Shr:
          case BinaryOperator::And:
          case BinaryOperator::Xor:
          case BinaryOperator::Or:
            // Not handled yet.
            return UnknownVal();
          case BinaryOperator::LT:
          case BinaryOperator::GT:
          case BinaryOperator::LE:
          case BinaryOperator::GE:
          case BinaryOperator::EQ:            
          case BinaryOperator::NE:
            opc = NegateComparison(opc);
            assert(symIntExpr->getType(ValMgr.getContext()) == resultTy);
            return ValMgr.makeNonLoc(symIntExpr->getLHS(), opc,
                                     symIntExpr->getRHS(), resultTy);
        }
      }
    }
    case nonloc::ConcreteIntKind: {   
      if (isa<nonloc::ConcreteInt>(rhs)) {
        const nonloc::ConcreteInt& lhsInt = cast<nonloc::ConcreteInt>(lhs);
        return lhsInt.evalBinOp(ValMgr, op, cast<nonloc::ConcreteInt>(rhs));
      }
      else {
        // Swap the left and right sides and flip the operator if doing so
        // allows us to better reason about the expression (this is a form
        // of expression canonicalization).
        NonLoc tmp = rhs;
        rhs = lhs;
        lhs = tmp;
        
        switch (op) {
          case BinaryOperator::LT: op = BinaryOperator::GT; continue;
          case BinaryOperator::GT: op = BinaryOperator::LT; continue;
          case BinaryOperator::LE: op = BinaryOperator::GE; continue;
          case BinaryOperator::GE: op = BinaryOperator::LE; continue;
          case BinaryOperator::EQ:
          case BinaryOperator::NE:
          case BinaryOperator::Add:
          case BinaryOperator::Mul:
            continue;
          default:
            return UnknownVal();
        }        
      }
    }
    case nonloc::SymbolValKind: {
      if (isa<nonloc::ConcreteInt>(rhs)) {
        return ValMgr.makeNonLoc(cast<nonloc::SymbolVal>(lhs).getSymbol(), op,
                                 cast<nonloc::ConcreteInt>(rhs).getValue(),
                                 resultTy);
      }

      return UnknownVal();
    }
    }
  }
}

SVal SimpleSValuator::EvalBinOpLL(BinaryOperator::Opcode op, Loc lhs, Loc rhs,
                                  QualType resultTy) {  
  switch (op) {
    default:
      return UnknownVal();
    case BinaryOperator::EQ:
    case BinaryOperator::NE:
      return EvalEquality(ValMgr, lhs, rhs, op == BinaryOperator::EQ, resultTy);
  }
}

SVal SimpleSValuator::EvalBinOpLN(const GRState *state,
                                  BinaryOperator::Opcode op,
                                  Loc lhs, NonLoc rhs, QualType resultTy) {  
  // Special case: 'rhs' is an integer that has the same width as a pointer and
  // we are using the integer location in a comparison.  Normally this cannot be
  // triggered, but transfer functions like those for OSCommpareAndSwapBarrier32
  // can generate comparisons that trigger this code.
  // FIXME: Are all locations guaranteed to have pointer width?
  if (BinaryOperator::isEqualityOp(op)) {
    if (nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs)) {
      const llvm::APSInt *x = &rhsInt->getValue();
      ASTContext &ctx = ValMgr.getContext();
      if (ctx.getTypeSize(ctx.VoidPtrTy) == x->getBitWidth()) {
        // Convert the signedness of the integer (if necessary).
        if (x->isSigned())
          x = &ValMgr.getBasicValueFactory().getValue(*x, true);          

        return EvalBinOpLL(op, lhs, loc::ConcreteInt(*x), resultTy);
      }
    }
  }
  
  // Delegate pointer arithmetic to the StoreManager.
  return state->getStateManager().getStoreManager().EvalBinOp(state, op, lhs,
                                                              rhs, resultTy);
}