LLVM API Documentation

SaveAndRestore.h
Go to the documentation of this file.
00001 //===-- SaveAndRestore.h - Utility  -------------------------------*- C++ -*-=//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 ///
00010 /// \file
00011 /// This file provides utility classes that use RAII to save and restore
00012 /// values.
00013 ///
00014 //===----------------------------------------------------------------------===//
00015 
00016 #ifndef LLVM_SUPPORT_SAVEANDRESTORE_H
00017 #define LLVM_SUPPORT_SAVEANDRESTORE_H
00018 
00019 namespace llvm {
00020 
00021 /// A utility class that uses RAII to save and restore the value of a variable.
00022 template <typename T> struct SaveAndRestore {
00023   SaveAndRestore(T &X) : X(X), OldValue(X) {}
00024   SaveAndRestore(T &X, const T &NewValue) : X(X), OldValue(X) {
00025     X = NewValue;
00026   }
00027   ~SaveAndRestore() { X = OldValue; }
00028   T get() { return OldValue; }
00029 
00030 private:
00031   T &X;
00032   T OldValue;
00033 };
00034 
00035 /// Similar to \c SaveAndRestore.  Operates only on bools; the old value of a
00036 /// variable is saved, and during the dstor the old value is or'ed with the new
00037 /// value.
00038 struct SaveOr {
00039   SaveOr(bool &X) : X(X), OldValue(X) { X = false; }
00040   ~SaveOr() { X |= OldValue; }
00041 
00042 private:
00043   bool &X;
00044   const bool OldValue;
00045 };
00046 
00047 } // namespace llvm
00048 
00049 #endif