summaryrefslogtreecommitdiff
path: root/clang/lib/Analysis/Interval.cpp
blob: 96dd8415ac05b5cdbc3d778c9bf2208758d4b38d (about) (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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
#include "clang/Analysis/Analyses/Interval.h"
#include "clang/AST/Stmt.h"
#include "clang/Analysis/CFG.h"
#include "clang/Analysis/AnalysisContext.h"
#include "clang/AST/StmtVisitor.h"

#include "clang/Analysis/Analyses/IntervalSolver/Log.hpp"
#include "clang/Analysis/Analyses/IntervalSolver/Complete.hpp"
#include "clang/Analysis/Analyses/IntervalSolver/VariableAssignment.hpp"
#include "clang/Analysis/Analyses/IntervalSolver/EquationSystem.hpp"
  
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/Process.h"
  
#include <deque>
#include <algorithm>
#include <vector>
#include <map>
#include <set>

using namespace clang;

#include <sstream>
template<typename T>
std::string toString(const T& obj) {
  std::stringstream stream;
  stream << obj;
  return stream.str();
}

#include <ostream>
template<typename K,typename V>
std::ostream& operator<<(std::ostream& cout, const std::pair<K,V>& v) {
  cout << "(" << v.first << ", " << v.second << ")";
  return cout;
}

template<typename K,typename V>
std::ostream& operator<<(std::ostream& cout, const std::map<K,V>& v) {
  cout << "{";
  for (typename std::map<K,V>::const_iterator it = v.begin(), ei = v.end();
       it != ei;
       ++it) {
    if (it != v.begin())
      cout << ", ";
    cout << it->first << ": " << it->second;
  }
  cout << "}";
  return cout;  
}


IntervalAnalysis :: IntervalAnalysis(AnalysisDeclContext &context)
  : context(&context) {
}

IntervalAnalysis :: ~IntervalAnalysis() {
}

// Two pieces of state:
//  -> condition protecting a node
//  -> node's expression itself
// We can then combine these in a straightforward way to
// get out equation system, whereupon we can solve for what
// we want to know. Then we can have program invariants!
//
// Hooray!

typedef Complete<int64_t> ZBar;
//typedef std::map<std::string, ZBar> Vector;

struct Vector : public std::map<std::string, ZBar> {
  Vector(const ZBar& val=infinity<ZBar>())
    : _val(val) { }
  ZBar operator[](const std::string& key) const {
    if (this->find(key) != this->end())
      return this->find(key)->second;
    return _val;
  }
  ZBar& operator[](const std::string& key) {
    if (this->find(key) != this->end())
      return this->find(key)->second;
    std::pair<iterator,bool> p = this->insert(std::pair<const std::string, ZBar>(key, _val));
    return p.first->second;
  }
  ZBar _val;
};

typedef std::pair<Vector, ZBar> Result; // a "slice" of an equation

//typedef std::map<std::string, Result> LinearEquation; // one `Result` per variable
struct LinearEquation : public std::map<std::string, Result> {
  Result operator[](const std::string& key) const {
    if (this->find(key) != this->end())
      return this->find(key)->second;
    Result r;
    r.first[key] = 1;
    r.second = 0;
    return r;
  }
  Result& operator[](const std::string& key) {
    if (this->find(key) != this->end())
      return this->find(key)->second;
    Result r;
    r.first[key] = 1;
    r.second = 0;
    std::pair<iterator,bool> p = this->insert(std::pair<const std::string, Result>(key, r));
    return p.first->second;
  }
};

typedef Vector Condition;

typedef EquationSystem<Vector> EqnSys;
typedef Expression<Vector> EqnExpr;
typedef Variable<Vector> EqnVar;


struct LinearOperator : public Operator<Vector> {
  LinearOperator(const LinearEquation& result)
    : _values(result) {}

  Vector eval(const std::vector<Vector>& vector) const {
    assert(vector.size() == 1);
    const Vector& v = vector[0];
    Vector result = v;
    for (LinearEquation::const_iterator it = _values.begin(),
           ei = _values.end();
         it != ei;
         ++it) {
      ZBar subresult = 0;
      for (Vector::const_iterator jt = it->second.first.begin(),
             ej = it->second.first.end();
           jt != ej;
           ++jt) {
        subresult += jt->second * v[jt->first];
      }
      subresult += it->second.second;
      result[it->first] = subresult;
    }
    return result;
  }

  void print(std::ostream& cout) const {
    cout << "linear[" << _values << "]";
  }

  LinearEquation _values;
};



template<class F, class M>
void transform_values(const F& f, M& map) {
  for (typename M::iterator it = map.begin(),
         ei = map.end();
       it != ei;
       ++it) {
    it->second = f(it->second);
  }
}

template<class M, class F> 
M merge_maps_with(const F& f, const M& left, const M& right) {
  M result;
  typename M::const_iterator first1 = left.begin(), last1 = left.end(),
    first2 = right.begin(), last2 = right.end();
  for (; first1 != last1 && first2 != last2;) {
    if (first2->first < first1->first) {
      result[first2->first] = first2->second;
      ++first2;
    } else if (first1->first == first2->first) {
      result[first1->first] = f(first1->second, first2->second);
      ++first1;
      ++first2;
    } else {
      result[first1->first] = first1->second;
      ++first1;
    }
  }
  while (first1 != last1) {
    result[first1->first] = first1->second;
    ++first1;
  }
  while (first2 != last2) {
    result[first2->first] = first2->second;
    ++first2;
  }
  return result;
}

template<>
Vector minimum(const Vector& l, const Vector& r) {
  return merge_maps_with(minimum<ZBar>, l, r);
}
template<class T>
T max(const T& l, const T& r) {
  return (l < r ? l : r);
}
template<class T>
T negate(const T& v) {
  return -v;
}
template<class T>
T addValues(const T& l, const T& r) {
  return l + r;
}

Vector operator-(const Vector& vector) {
  Vector result(-vector._val);
  for (Vector::const_iterator it = vector.begin(),
         ei = vector.end();
       it != ei;
       ++it) {
    result[it->first] = -it->second;
  }
  return result;
}

Vector operator+(const Vector& left, const Vector& right) {
  return merge_maps_with(addValues<ZBar>, left, right);
}

Vector operator-(const Vector& left, const Vector& right) {
  return merge_maps_with(addValues<ZBar>, left, -right);
}

Vector operator*(const Vector& left, const ZBar& right) {
  Vector result;
  for (Vector::const_iterator it = left.begin(),
         ei = left.end();
       it != ei;
       ++it) {
    result[it->first] = (it->second * right);
  }
  return result;
}
Vector operator*(const ZBar& left, const Vector& right) {
  return right * left;
}
bool operator<(const Vector& left, const Vector& right) {
  for (Vector::const_iterator it = left.begin(),
         ei = left.end();
       it != ei;
       ++it) {
    if (it->second < right[it->first]) {
      return true;
    }
  }
  for (Vector::const_iterator it = right.begin(),
         ei = right.end();
       it != ei;
       ++it) {
    if (left[it->first] < it->second) {
      return true;
    }
  }
  return false;
}

template<>
Vector infinity<Vector>() {
  return Vector(infinity<ZBar>());
}

std::ostream& operator<<(std::ostream& cout, const Vector& v) {
  cout << "{";
  for (Vector::const_iterator it = v.begin(), ei = v.end();
       it != ei;
       ++it) {
    cout << it->first << ": " << it->second << ", ";
  }
  cout << "_: " << v._val;
  cout << "}";
  return cout;
}


Result fromStmt(const Stmt*);

Result fromInteger(const IntegerLiteral* expr) {
  return Result(Vector(), *expr->getValue().getRawData());
}

Result fromDeclExpr(const DeclRefExpr* expr) {
  Vector val;
  val[expr->getNameInfo().getAsString()] = 1;
  return Result(val, 0);
}

Result fromUnary(const UnaryOperator* op) {
  switch (op->getOpcode()) {
  case UO_PreInc:
    break;
  case UO_PostInc:
    break;
  }
  return Result(Vector(), 0);
}

Result fromBinary(const BinaryOperator* op) {
  Result left = fromStmt(op->getLHS()->IgnoreParenCasts());
  Result right = fromStmt(op->getRHS()->IgnoreParenCasts());
  
  switch (op->getOpcode()) {
  case BO_Assign:
    return right;
  case BO_Sub:
    transform_values(negate<ZBar>, right.first);
    right.second *= -1;
  case BO_Add:
    {
      Result result;
      result.first = merge_maps_with(addValues<ZBar>,
                                     left.first, right.first);
      result.second = left.second + right.second;
      return result;
    }
  case BO_Mul:
    {
      if (!left.first.empty() && !right.first.empty()) {
        return Result(Vector(), 0);
      }
      ZBar scalar = 0;
      Result value;
      if (left.first.empty()) {
        scalar = left.second;
        value = right;
      } else {
        scalar = right.second;
        value = left;
      }
      if (scalar > 0) {
        for (Vector::iterator it = value.first.begin(),
               ei = value.first.end();
             it != ei;
             ++it) {
          it->second *= scalar;
        }
      } else {
        Vector newValue;
        for (Vector::iterator it = value.first.begin(),
               ei = value.first.end();
             it != ei;
             ++it) {
          std::string name;
          if (it->first[0] == '-') {
            name = it->first.substr(1);
          } else {
            name = '-' + it->first;
          }
          newValue[name] = (-scalar) * it->second;
        }
      }
      right.second *= scalar;
      return value;
    }
  case BO_LT:
  case BO_LE:
  case BO_GT:
  case BO_GE:
    break;
  } 
  return Result();
}

Result fromDeclStmt(const DeclStmt* stmt) {
  for (DeclStmt::const_decl_iterator it = stmt->decl_begin(),
                                     ei = stmt->decl_end();
       it != ei;
       ++it) {
    if ((*it)->getKind() == Decl::Var) {
      const VarDecl* decl = static_cast<const VarDecl*>(*it);
      llvm::errs() << decl->getNameAsString() << " = ";

      Result expr = fromStmt(decl->getInit());
      for (Vector::iterator it = expr.first.begin(),
             ei = expr.first.end();
           it != ei;
           ++it) {
        if (it != expr.first.begin())
          llvm::errs() << " + ";
        llvm::errs() << toString(it->second) << "*" << toString(it->first);
      }
      llvm::errs() << " + " << toString(expr.second) << "\n";


      llvm::errs() << "-" << decl->getNameAsString() << " = ";
      for (Vector::iterator it = expr.first.begin(),
             ei = expr.first.end();
           it != ei;
           ++it) {
        if (it != expr.first.begin())
          llvm::errs() << " + ";
        llvm::errs() << toString(it->second) << "*" << toString(it->first);
      }
      llvm::errs() << " - " << toString(expr.second) << "\n";
    }
  }

  return Result();
}

Result fromAssignment(const BinaryOperator* op) {
  const Expr* left = op->getLHS()->IgnoreParenCasts();
  if (left->getStmtClass() == Stmt::DeclRefExprClass) {
    std::string name = static_cast<const DeclRefExpr*>(left)->getNameInfo().getAsString();

    Result expr = fromStmt(op->getRHS()->IgnoreParenCasts());
    llvm::errs() << name << " = ";
    for (Vector::iterator it = expr.first.begin(),
           ei = expr.first.end();
         it != ei;
         ++it) {
      if (it != expr.first.begin())
        llvm::errs() << " + ";
      llvm::errs() << toString(it->second) << "*" << toString(it->first);
    }
    llvm::errs() << " + " << toString(expr.second) << "\n";
    return expr;
  }
  return Result();
}

Result fromStmt(const Stmt* stmt) {
  if (!stmt)
    return Result();
  //stmt->dump();
  switch (stmt->getStmtClass()) {
  case Stmt::IntegerLiteralClass:
    return fromInteger(static_cast<const IntegerLiteral*>(stmt));
  case Stmt::DeclRefExprClass:
    return fromDeclExpr(static_cast<const DeclRefExpr*>(stmt));
  case Stmt::UnaryOperatorClass:
    return fromUnary(static_cast<const UnaryOperator*>(stmt));
  case Stmt::DeclStmtClass:
    return fromDeclStmt(static_cast<const DeclStmt*>(stmt));
  case Stmt::BinaryOperatorClass:
    return fromBinary(static_cast<const BinaryOperator*>(stmt));
  }
  const Expr* expr = dyn_cast<const Expr>(stmt);
  if (expr) {
    const Expr* expr2 = expr->IgnoreParenCasts();
    if (expr != expr2)
      return fromStmt(expr2);
  }
  llvm::errs() << "we shouldn't get here...\n";
  return Result();
}

Condition fromComparison(const BinaryOperator* op) {
  if (op->isRelationalOp()) {
    const Expr* left = op->getLHS()->IgnoreParenCasts();
    const Expr* right = op->getRHS()->IgnoreParenCasts();

    Condition cond;
    std::string name;
    int64_t value;
    if (left->getStmtClass() == Stmt::DeclRefExprClass) {
      if (right->getStmtClass() == Stmt::IntegerLiteralClass) {
        name = static_cast<const DeclRefExpr*>(left)->getNameInfo().getAsString();
        value = *static_cast<const IntegerLiteral*>(right)->getValue().getRawData();
        switch (op->getOpcode()) {
        case BO_LT:
          cond[name] = value - 1;
          break;
        case BO_LE:
          cond[name] = value;
          break;
        case BO_GE:
          cond['-' + name] = -value;
          break;
        case BO_GT:
          cond['-' + name] = -(value + 1);
          break;
        }
        return cond;
      } else {
        return Condition();
      }
    } else if (right->getStmtClass() == Stmt::DeclRefExprClass) {
      if (left->getStmtClass() == Stmt::IntegerLiteralClass) {
        name = static_cast<const DeclRefExpr*>(right)->getNameInfo().getAsString();
        value = *static_cast<const IntegerLiteral*>(left)->getValue().getRawData();
        switch (op->getOpcode()) {
        case BO_LT:
          cond['-' + name] = -(value + 1);
          break;
        case BO_LE:
          cond['-' + name] = -value;
          break;
        case BO_GE:
          cond[name] = value;
          break;
        case BO_GT:
          cond[name] = value - 1;
          break;
        }
        return cond;
      } else {
        return Condition();
      }
    }
    return Condition();
  }
  return Condition();
}

std::map<const CFGBlock*, EqnVar*> seen_blocks;
EqnVar* runOnBlock(const CFGBlock* block, EqnSys& system) {
  if (seen_blocks.find(block) != seen_blocks.end())
    return seen_blocks.find(block)->second;

  std::string id = toString(block->getBlockID());
  unsigned int counter = 0;
  
  // detemine equations for this block
  LinearEquation eqn;
  EqnVar* var;
  Result current;

  var = &system.variable(id);
  for (CFGBlock::const_iterator it = block->begin(),
                                ei = block->end();
       it != ei;
       ++it) {
    const CFGStmt* cfg_stmt = it->getAs<CFGStmt>();
    const Stmt* stmt = cfg_stmt->getStmt();

    std::string name = "";
    Result expr;
    if (stmt->getStmtClass() == Stmt::BinaryOperatorClass) {
      const BinaryOperator* binop = static_cast<const BinaryOperator*>(stmt);
      if (binop->isAssignmentOp()) {
        const Expr* left = binop->getLHS()->IgnoreParenCasts();
        const Expr* right = binop->getRHS()->IgnoreParenCasts();
        if (left->getStmtClass() == Stmt::DeclRefExprClass) {
          name = static_cast<const DeclRefExpr*>(left)->getNameInfo().getAsString();
          expr = fromStmt(right);
        }
      }
    } else if (stmt->getStmtClass() == Stmt::DeclStmtClass) {
      stmt->dump();
      const DeclStmt* decl_stmt = static_cast<const DeclStmt*>(stmt);
      for (DeclStmt::const_decl_iterator jt = decl_stmt->decl_begin(),
             ej = decl_stmt->decl_end();
           jt != ej;
           ++jt) {
        if ((*jt)->getKind() == Decl::Var) {
          const VarDecl* decl = static_cast<const VarDecl*>(*jt);
          name = decl->getNameAsString();
          expr = fromStmt(decl->getInit());
          if (jt+1 != ej) {
            llvm::errs() << "Only the first declaration in a multi-declaration statement is used.\n";
          }
          llvm::errs() << "Name: " << name << "\n";
          llvm::errs() << toString(expr) << "\n";
          break; // only take the first one, for now
        } else {
          llvm::errs() << (*jt)->getDeclKindName() << "\n";
        }
      }
    }
    if (name == "")
      continue;

    // by here we expect `name` and `expr` to be set correctly

    bool newBlock = false;
    for (Vector::const_iterator jt = expr.first.begin(),
           ej = expr.first.end();
         jt != ej;
         ++jt) {
      // new block if we read from any variable we've already written to
      newBlock |= (eqn.find(jt->first) != eqn.end());
    }

    if (newBlock) {
      EqnVar* lastVar = var;
      var = &system.variable(id + "-" + toString(++counter));

      // the linear expression
      std::vector<EqnExpr*> args;
      args.push_back(lastVar);
      EqnExpr* expr = &system.expression(new LinearOperator(eqn), args);

      // the max expression
      std::vector<EqnExpr*> maxArgs;
      maxArgs.push_back(&system.constant(-infinity<Vector>()));
      maxArgs.push_back(expr);
      system[*var] = &system.maxExpression(args);
      eqn = LinearEquation();
    }

    eqn[name] = expr;
    expr.first = expr.first;
    expr.second = -expr.second;
    eqn["-"+name] = expr;
  }

  EqnVar* lastVar = var;
  var = &system.variable(id + "-" + toString(++counter));

  // the linear expression
  std::vector<EqnExpr*> args;
  args.push_back(lastVar);
  EqnExpr* expr = &system.expression(new LinearOperator(eqn), args);

  // the max expression
  std::vector<EqnExpr*> maxArgs;
  maxArgs.push_back(&system.constant(-infinity<Vector>()));
  maxArgs.push_back(expr);
  system[*var] = &system.maxExpression(maxArgs);

  // save the last variable we used (the final values from this block)
  seen_blocks[block] = var;

  // determine predecessor variables/conditions
  // we have to do this last to prevent an infinite loop situation
  std::vector<EqnExpr*> preArgs;
  for (CFGBlock::const_pred_iterator it = block->pred_begin(),
         ei = block->pred_end();
       it != ei;
       ++it) {
    if ((*it)->getTerminatorCondition()) {
      const BinaryOperator* binop = static_cast<const BinaryOperator*>((*it)->getTerminatorCondition());
      std::vector<EqnExpr*> args;
      args.push_back(&system.constant(fromComparison(binop)));
      args.push_back(runOnBlock(*it, system));
      preArgs.push_back(&system.expression(new Minimum<Vector>(), args));
    } else {
      preArgs.push_back(runOnBlock(*it, system));
    }
  }
  EqnVar* preVar = &system.variable(id);
  if (preArgs.empty())
    preArgs.push_back(&system.constant(infinity<Vector>()));
  system[*preVar] = &system.maxExpression(preArgs);

  // return the final value we used
  return var;
}

void IntervalAnalysis::runOnAllBlocks() {
  llvm::errs() << "Enter run on all blocks\n";

  const CFG *cfg = this->context->getCFG();

  EqnSys system;

  std::set<const CFGBlock*> seen;
  std::deque<const CFGBlock*> todo;
  todo.push_back(&cfg->getEntry());

  while (!todo.empty()) {
    const CFGBlock* block = todo.front();
    if (seen.find(todo.front()) != seen.end()) {
      todo.pop_front();
      continue;
    }
    llvm::errs() << block->getBlockID() << "\n";
    seen.insert(block);
    todo.pop_front();
    runOnBlock(block, system);
    llvm::errs() << "-> ";
    for (CFGBlock::const_succ_iterator it = block->succ_begin(),
                                       ei = block->succ_end();
         it != ei;
         it++ ) {
      llvm::errs() << (*it)->getBlockID() << ", ";
      todo.push_back(*it);
    }
    llvm::errs() << "\n\n";
  }

  llvm::errs() << "Exit run on all blocks\n";

  llvm::errs() << toString(system) << "\n";

  system.indexMaxExpressions();
  DynamicMaxStrategy<Vector> strategy(system);
  DynamicVariableAssignment<Vector> rho(system, strategy);
  strategy.setRho(rho);

  for (unsigned int i = 0, size = system.variableCount(); i < size; ++i) {
    Variable<Vector>& var = system.variable(i);
    llvm::errs() << toString(var.name()) << " = " << toString(rho[var]) << "\n";
  }

  //  cfg->dump(context->getASTContext().getLangOpts(),
  //            llvm::sys::Process::StandardErrHasColors());
}


const void *IntervalAnalysis::getTag() { static int x; return &x; }