Evaluator.h 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- Evaluator.h - LLVM IR evaluator --------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // Function evaluator for LLVM IR.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_TRANSFORMS_UTILS_EVALUATOR_H
  18. #define LLVM_TRANSFORMS_UTILS_EVALUATOR_H
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/IR/BasicBlock.h"
  23. #include "llvm/IR/GlobalVariable.h"
  24. #include "llvm/Support/Casting.h"
  25. #include <cassert>
  26. #include <deque>
  27. #include <memory>
  28. namespace llvm {
  29. class CallBase;
  30. class DataLayout;
  31. class Function;
  32. class TargetLibraryInfo;
  33. /// This class evaluates LLVM IR, producing the Constant representing each SSA
  34. /// instruction. Changes to global variables are stored in a mapping that can
  35. /// be iterated over after the evaluation is complete. Once an evaluation call
  36. /// fails, the evaluation object should not be reused.
  37. class Evaluator {
  38. struct MutableAggregate;
  39. /// The evaluator represents values either as a Constant*, or as a
  40. /// MutableAggregate, which allows changing individual aggregate elements
  41. /// without creating a new interned Constant.
  42. class MutableValue {
  43. PointerUnion<Constant *, MutableAggregate *> Val;
  44. void clear();
  45. bool makeMutable();
  46. public:
  47. MutableValue(Constant *C) { Val = C; }
  48. MutableValue(const MutableValue &) = delete;
  49. MutableValue(MutableValue &&Other) {
  50. Val = Other.Val;
  51. Other.Val = nullptr;
  52. }
  53. ~MutableValue() { clear(); }
  54. Type *getType() const {
  55. if (auto *C = Val.dyn_cast<Constant *>())
  56. return C->getType();
  57. return Val.get<MutableAggregate *>()->Ty;
  58. }
  59. Constant *toConstant() const {
  60. if (auto *C = Val.dyn_cast<Constant *>())
  61. return C;
  62. return Val.get<MutableAggregate *>()->toConstant();
  63. }
  64. Constant *read(Type *Ty, APInt Offset, const DataLayout &DL) const;
  65. bool write(Constant *V, APInt Offset, const DataLayout &DL);
  66. };
  67. struct MutableAggregate {
  68. Type *Ty;
  69. SmallVector<MutableValue> Elements;
  70. MutableAggregate(Type *Ty) : Ty(Ty) {}
  71. Constant *toConstant() const;
  72. };
  73. public:
  74. Evaluator(const DataLayout &DL, const TargetLibraryInfo *TLI)
  75. : DL(DL), TLI(TLI) {
  76. ValueStack.emplace_back();
  77. }
  78. ~Evaluator() {
  79. for (auto &Tmp : AllocaTmps)
  80. // If there are still users of the alloca, the program is doing something
  81. // silly, e.g. storing the address of the alloca somewhere and using it
  82. // later. Since this is undefined, we'll just make it be null.
  83. if (!Tmp->use_empty())
  84. Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
  85. }
  86. /// Evaluate a call to function F, returning true if successful, false if we
  87. /// can't evaluate it. ActualArgs contains the formal arguments for the
  88. /// function.
  89. bool EvaluateFunction(Function *F, Constant *&RetVal,
  90. const SmallVectorImpl<Constant*> &ActualArgs);
  91. DenseMap<GlobalVariable *, Constant *> getMutatedInitializers() const {
  92. DenseMap<GlobalVariable *, Constant *> Result;
  93. for (const auto &Pair : MutatedMemory)
  94. Result[Pair.first] = Pair.second.toConstant();
  95. return Result;
  96. }
  97. const SmallPtrSetImpl<GlobalVariable *> &getInvariants() const {
  98. return Invariants;
  99. }
  100. private:
  101. bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB,
  102. bool &StrippedPointerCastsForAliasAnalysis);
  103. Constant *getVal(Value *V) {
  104. if (Constant *CV = dyn_cast<Constant>(V)) return CV;
  105. Constant *R = ValueStack.back().lookup(V);
  106. assert(R && "Reference to an uncomputed value!");
  107. return R;
  108. }
  109. void setVal(Value *V, Constant *C) {
  110. ValueStack.back()[V] = C;
  111. }
  112. /// Casts call result to a type of bitcast call expression
  113. Constant *castCallResultIfNeeded(Type *ReturnType, Constant *RV);
  114. /// Given call site return callee and list of its formal arguments
  115. Function *getCalleeWithFormalArgs(CallBase &CB,
  116. SmallVectorImpl<Constant *> &Formals);
  117. /// Given call site and callee returns list of callee formal argument
  118. /// values converting them when necessary
  119. bool getFormalParams(CallBase &CB, Function *F,
  120. SmallVectorImpl<Constant *> &Formals);
  121. Constant *ComputeLoadResult(Constant *P, Type *Ty);
  122. Constant *ComputeLoadResult(GlobalVariable *GV, Type *Ty,
  123. const APInt &Offset);
  124. /// As we compute SSA register values, we store their contents here. The back
  125. /// of the deque contains the current function and the stack contains the
  126. /// values in the calling frames.
  127. std::deque<DenseMap<Value*, Constant*>> ValueStack;
  128. /// This is used to detect recursion. In pathological situations we could hit
  129. /// exponential behavior, but at least there is nothing unbounded.
  130. SmallVector<Function*, 4> CallStack;
  131. /// For each store we execute, we update this map. Loads check this to get
  132. /// the most up-to-date value. If evaluation is successful, this state is
  133. /// committed to the process.
  134. DenseMap<GlobalVariable *, MutableValue> MutatedMemory;
  135. /// To 'execute' an alloca, we create a temporary global variable to represent
  136. /// its body. This vector is needed so we can delete the temporary globals
  137. /// when we are done.
  138. SmallVector<std::unique_ptr<GlobalVariable>, 32> AllocaTmps;
  139. /// These global variables have been marked invariant by the static
  140. /// constructor.
  141. SmallPtrSet<GlobalVariable*, 8> Invariants;
  142. /// These are constants we have checked and know to be simple enough to live
  143. /// in a static initializer of a global.
  144. SmallPtrSet<Constant*, 8> SimpleConstants;
  145. const DataLayout &DL;
  146. const TargetLibraryInfo *TLI;
  147. };
  148. } // end namespace llvm
  149. #endif // LLVM_TRANSFORMS_UTILS_EVALUATOR_H
  150. #ifdef __GNUC__
  151. #pragma GCC diagnostic pop
  152. #endif