SaveAndRestore.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //===-- SaveAndRestore.h - Utility -------------------------------*- 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. /// \file
  11. /// This file provides utility classes that use RAII to save and restore
  12. /// values.
  13. ///
  14. //===----------------------------------------------------------------------===//
  15. #ifndef LLVM_SUPPORT_SAVEANDRESTORE_H
  16. #define LLVM_SUPPORT_SAVEANDRESTORE_H
  17. namespace llvm {
  18. /// A utility class that uses RAII to save and restore the value of a variable.
  19. template <typename T> struct SaveAndRestore {
  20. SaveAndRestore(T &X) : X(X), OldValue(X) {}
  21. SaveAndRestore(T &X, const T &NewValue) : X(X), OldValue(X) {
  22. X = NewValue;
  23. }
  24. ~SaveAndRestore() { X = OldValue; }
  25. T get() { return OldValue; }
  26. private:
  27. T &X;
  28. T OldValue;
  29. };
  30. /// Similar to \c SaveAndRestore. Operates only on bools; the old value of a
  31. /// variable is saved, and during the dstor the old value is or'ed with the new
  32. /// value.
  33. struct SaveOr {
  34. SaveOr(bool &X) : X(X), OldValue(X) { X = false; }
  35. ~SaveOr() { X |= OldValue; }
  36. private:
  37. bool &X;
  38. const bool OldValue;
  39. };
  40. } // namespace llvm
  41. #endif