ValueLattice.cpp 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //===- ValueLattice.cpp - Value constraint analysis -------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/Analysis/ValueLattice.h"
  9. #include "llvm/Analysis/ConstantFolding.h"
  10. namespace llvm {
  11. Constant *
  12. ValueLatticeElement::getCompare(CmpInst::Predicate Pred, Type *Ty,
  13. const ValueLatticeElement &Other,
  14. const DataLayout &DL) const {
  15. // Not yet resolved.
  16. if (isUnknown() || Other.isUnknown())
  17. return nullptr;
  18. // TODO: Can be made more precise, but always returning undef would be
  19. // incorrect.
  20. if (isUndef() || Other.isUndef())
  21. return nullptr;
  22. if (isConstant() && Other.isConstant())
  23. return ConstantFoldCompareInstOperands(Pred, getConstant(),
  24. Other.getConstant(), DL);
  25. if (ICmpInst::isEquality(Pred)) {
  26. // not(C) != C => true, not(C) == C => false.
  27. if ((isNotConstant() && Other.isConstant() &&
  28. getNotConstant() == Other.getConstant()) ||
  29. (isConstant() && Other.isNotConstant() &&
  30. getConstant() == Other.getNotConstant()))
  31. return Pred == ICmpInst::ICMP_NE ? ConstantInt::getTrue(Ty)
  32. : ConstantInt::getFalse(Ty);
  33. }
  34. // Integer constants are represented as ConstantRanges with single
  35. // elements.
  36. if (!isConstantRange() || !Other.isConstantRange())
  37. return nullptr;
  38. const auto &CR = getConstantRange();
  39. const auto &OtherCR = Other.getConstantRange();
  40. if (CR.icmp(Pred, OtherCR))
  41. return ConstantInt::getTrue(Ty);
  42. if (CR.icmp(CmpInst::getInversePredicate(Pred), OtherCR))
  43. return ConstantInt::getFalse(Ty);
  44. return nullptr;
  45. }
  46. raw_ostream &operator<<(raw_ostream &OS, const ValueLatticeElement &Val) {
  47. if (Val.isUnknown())
  48. return OS << "unknown";
  49. if (Val.isUndef())
  50. return OS << "undef";
  51. if (Val.isOverdefined())
  52. return OS << "overdefined";
  53. if (Val.isNotConstant())
  54. return OS << "notconstant<" << *Val.getNotConstant() << ">";
  55. if (Val.isConstantRangeIncludingUndef())
  56. return OS << "constantrange incl. undef <"
  57. << Val.getConstantRange(true).getLower() << ", "
  58. << Val.getConstantRange(true).getUpper() << ">";
  59. if (Val.isConstantRange())
  60. return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
  61. << Val.getConstantRange().getUpper() << ">";
  62. return OS << "constant<" << *Val.getConstant() << ">";
  63. }
  64. } // end namespace llvm