1 //=- Serialization.h - Generic Object Serialization to Bitcode ---*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Ted Kremenek and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interface for generic object serialization to
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_BITCODE_SERIALIZE
16 #define LLVM_BITCODE_SERIALIZE
18 #include "llvm/Bitcode/BitstreamWriter.h"
19 #include "llvm/Bitcode/BitstreamReader.h"
20 #include "llvm/ADT/SmallVector.h"
25 template <typename T> struct SerializeTrait;
28 BitstreamWriter& Stream;
29 SmallVector<uint64_t,10> Record;
32 Serializer(BitstreamWriter& stream, unsigned BlockID = 0);
36 inline void Emit(const T& X) { SerializeTrait<T>::Serialize(*this,X); }
38 void EmitInt(unsigned X, unsigned bits);
40 // FIXME: Substitute a better implementation which calculates the minimum
41 // number of bits needed to serialize the enum.
42 void EmitEnum(unsigned X, unsigned MinVal, unsigned MaxVal) { EmitInt(X,32); }
44 void EmitCString(const char* cstr);
46 void Flush() { if (inRecord()) EmitRecord(); }
50 inline bool inRecord() { return Record.size() > 0; }
55 BitstreamReader& Stream;
56 SmallVector<uint64_t,10> Record;
59 Deserializer(BitstreamReader& stream);
63 inline T& Read(T& X) { SerializeTrait<T>::Deserialize(*this,X); return X; }
66 inline T* Materialize() {
67 T* X = SerializeTrait<T>::Instantiate();
72 uint64_t ReadInt(unsigned bits = 32);
73 bool ReadBool() { return ReadInt(1) ? true : false; }
75 // FIXME: Substitute a better implementation which calculates the minimum
76 // number of bits needed to serialize the enum.
77 template <typename EnumT>
78 EnumT ReadEnum(unsigned MinVal, unsigned MaxVal) {
79 return static_cast<EnumT>(ReadInt(32));
82 char* ReadCString(char* cstr = NULL, unsigned MaxLen=0, bool isNullTerm=true);
83 void ReadCString(std::vector<char>& buff, bool isNullTerm=false);
88 inline bool inRecord() {
89 if (Record.size() > 0) {
90 if (RecIdx >= Record.size()) {
102 template <typename uintty, unsigned Bits>
103 struct SerializeIntTrait {
104 static inline void Serialize(Serializer& S, uintty X) {
108 static inline void Deserialize(Deserializer& S, uintty& X) {
109 X = (uintty) S.ReadInt(Bits);
113 template <> struct SerializeTrait<bool>
114 : public SerializeIntTrait<bool,1> {};
116 template <> struct SerializeTrait<char>
117 : public SerializeIntTrait<char,8> {};
119 template <> struct SerializeTrait<short>
120 : public SerializeIntTrait<short,16> {};
122 template <> struct SerializeTrait<unsigned>
123 : public SerializeIntTrait<unsigned,32> {};
127 } // end namespace llvm