Added support in serializer and deserializer to create arbitrary blocks.
[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 was developed by Ted Kremenek and is distributed under the
6 // University of Illinois Open Source 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 "string.h"
16
17 using namespace llvm;
18
19 Serializer::Serializer(BitstreamWriter& stream, unsigned BlockID)
20   : Stream(stream), BlockLevel(0) {
21     
22   if (BlockID >= 8)
23     EnterBlock(8,3);
24 }
25
26 Serializer::~Serializer() {
27   if (inRecord())
28     EmitRecord();
29
30   while (BlockLevel > 0)
31     Stream.ExitBlock();
32   
33   Stream.FlushToWord();
34 }
35
36 void Serializer::EmitRecord() {
37   assert(Record.size() > 0 && "Cannot emit empty record.");
38   Stream.EmitRecord(8,Record);
39   Record.clear();
40 }
41
42 void Serializer::EnterBlock(unsigned BlockID,unsigned CodeLen) {
43   Flush();
44   Stream.EnterSubblock(BlockID,CodeLen);
45   ++BlockLevel;
46 }
47
48 void Serializer::ExitBlock() {
49   assert (BlockLevel > 0);
50   --BlockLevel;
51   Flush();
52   Stream.ExitBlock();
53 }
54
55 void Serializer::EmitInt(unsigned X) {
56   assert (BlockLevel > 0);
57   Record.push_back(X);
58 }
59
60 void Serializer::EmitCStr(const char* s, const char* end) {
61   Record.push_back(end - s);
62   
63   while(s != end) {
64     Record.push_back(*s);
65     ++s;
66   }
67
68   EmitRecord();
69 }
70
71 void Serializer::EmitCStr(const char* s) {
72   EmitCStr(s,s+strlen(s));
73 }
74
75 unsigned Serializer::getPtrId(const void* ptr) {
76   if (!ptr)
77     return 0;
78   
79   MapTy::iterator I = PtrMap.find(ptr);
80   
81   if (I == PtrMap.end()) {
82     unsigned id = PtrMap.size()+1;
83     PtrMap[ptr] = id;
84     return id;
85   }
86   else return I->second;
87 }
88
89
90 #define INT_EMIT(TYPE)\
91 void SerializeTrait<TYPE>::Emit(Serializer&S, TYPE X) { S.EmitInt(X); }
92
93 INT_EMIT(bool)
94 INT_EMIT(unsigned char)
95 INT_EMIT(unsigned short)
96 INT_EMIT(unsigned int)
97 INT_EMIT(unsigned long)