Fix a comment typo.
[oota-llvm.git] / lib / Bitcode / Writer / Serialize.cpp
1 //==- Serialize.cpp - Generic Object Serialization to Bitcode ----*- 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 // This file defines the internal methods used for object serialization.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Bitcode/Serialize.h"
15 #include "llvm/Support/raw_ostream.h"
16 #include <cstring>
17
18 using namespace llvm;
19
20 Serializer::Serializer(BitstreamWriter& stream)
21   : Stream(stream), BlockLevel(0) {}
22
23 Serializer::~Serializer() {
24   if (inRecord())
25     EmitRecord();
26
27   while (BlockLevel > 0)
28     Stream.ExitBlock();
29    
30   Stream.FlushToWord();
31 }
32
33 void Serializer::EmitRecord() {
34   assert(Record.size() > 0 && "Cannot emit empty record.");
35   Stream.EmitRecord(8,Record);
36   Record.clear();
37 }
38
39 void Serializer::EnterBlock(unsigned BlockID,unsigned CodeLen) {
40   FlushRecord();
41   Stream.EnterSubblock(BlockID,CodeLen);
42   ++BlockLevel;
43 }
44
45 void Serializer::ExitBlock() {
46   assert (BlockLevel > 0);
47   --BlockLevel;
48   FlushRecord();
49   Stream.ExitBlock();
50 }
51
52 void Serializer::EmitInt(uint64_t X) {
53   assert (BlockLevel > 0);
54   Record.push_back(X);
55 }
56
57 void Serializer::EmitSInt(int64_t X) {
58   if (X >= 0)
59     EmitInt(X << 1);
60   else
61     EmitInt((-X << 1) | 1);
62 }
63
64 void Serializer::EmitCStr(const char* s, const char* end) {
65   Record.push_back(end - s);
66   
67   while(s != end) {
68     Record.push_back(*s);
69     ++s;
70   }
71 }
72
73 void Serializer::EmitCStr(const char* s) {
74   EmitCStr(s,s+strlen(s));
75 }
76
77 SerializedPtrID Serializer::getPtrId(const void* ptr) {
78   if (!ptr)
79     return 0;
80   
81   MapTy::iterator I = PtrMap.find(ptr);
82   
83   if (I == PtrMap.end()) {
84     unsigned id = PtrMap.size()+1;
85 #ifdef DEBUG_BACKPATCH
86     errs() << "Registered PTR: " << ptr << " => " << id << "\n";
87 #endif
88     PtrMap[ptr] = id;
89     return id;
90   }
91   else return I->second;
92 }
93
94 bool Serializer::isRegistered(const void* ptr) const {
95   MapTy::const_iterator I = PtrMap.find(ptr);
96   return I != PtrMap.end();
97 }
98
99
100 #define INT_EMIT(TYPE)\
101 void SerializeTrait<TYPE>::Emit(Serializer&S, TYPE X) { S.EmitInt(X); }
102
103 INT_EMIT(bool)
104 INT_EMIT(unsigned char)
105 INT_EMIT(unsigned short)
106 INT_EMIT(unsigned int)
107 INT_EMIT(unsigned long)
108
109 #define SINT_EMIT(TYPE)\
110 void SerializeTrait<TYPE>::Emit(Serializer&S, TYPE X) { S.EmitSInt(X); }
111
112 SINT_EMIT(signed char)
113 SINT_EMIT(signed short)
114 SINT_EMIT(signed int)
115 SINT_EMIT(signed long)