Fix constness problem
[oota-llvm.git] / lib / Bytecode / Writer / Writer.cpp
1 //===-- Writer.cpp - Library for writing VM bytecode files -------*- C++ -*--=//
2 //
3 // This library implements the functionality defined in llvm/Bytecode/Writer.h
4 //
5 // Note that this file uses an unusual technique of outputting all the bytecode
6 // to a deque of unsigned char's, then copies the deque to an ostream.  The
7 // reason for this is that we must do "seeking" in the stream to do back-
8 // patching, and some very important ostreams that we want to support (like
9 // pipes) do not support seeking.  :( :( :(
10 //
11 // The choice of the deque data structure is influenced by the extremely fast
12 // "append" speed, plus the free "seek"/replace in the middle of the stream. I
13 // didn't use a vector because the stream could end up very large and copying
14 // the whole thing to reallocate would be kinda silly.
15 //
16 // Note that the performance of this library is not terribly important, because
17 // it shouldn't be used by JIT type applications... so it is not a huge focus
18 // at least.  :)
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "WriterInternals.h"
23 #include "llvm/Module.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Function.h"
26 #include "llvm/BasicBlock.h"
27 #include "llvm/SymbolTable.h"
28 #include "llvm/DerivedTypes.h"
29 #include "Support/STLExtras.h"
30 #include <string.h>
31 #include <algorithm>
32
33 BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M) 
34   : Out(o), Table(M, false) {
35
36   outputSignature();
37
38   // Emit the top level CLASS block.
39   BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
40
41   // Output the ID of first "derived" type:
42   output_vbr((unsigned)Type::FirstDerivedTyID, Out);
43   align32(Out);
44
45   // Output module level constants, including types used by the function protos
46   outputConstants(false);
47
48   // The ModuleInfoBlock follows directly after the Module constant pool
49   outputModuleInfoBlock(M);
50
51   // Do the whole module now! Process each function at a time...
52   for_each(M->begin(), M->end(),
53            bind_obj(this, &BytecodeWriter::processMethod));
54
55   // If needed, output the symbol table for the module...
56   if (M->hasSymbolTable())
57     outputSymbolTable(*M->getSymbolTable());
58 }
59
60 void BytecodeWriter::outputConstants(bool isFunction) {
61   BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
62
63   unsigned NumPlanes = Table.getNumPlanes();
64   for (unsigned pno = 0; pno < NumPlanes; pno++) {
65     const std::vector<const Value*> &Plane = Table.getPlane(pno);
66     if (Plane.empty()) continue;      // Skip empty type planes...
67
68     unsigned ValNo = 0;
69     if (isFunction)                   // Don't reemit module constants
70       ValNo = Table.getModuleLevel(pno);
71     else if (pno == Type::TypeTyID)
72       ValNo = Type::FirstDerivedTyID; // Start emitting at the derived types...
73     
74     // Scan through and ignore function arguments...
75     for (; ValNo < Plane.size() && isa<Argument>(Plane[ValNo]); ValNo++)
76       /*empty*/;
77
78     unsigned NC = ValNo;              // Number of constants
79     for (; NC < Plane.size() && 
80            (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
81       /*empty*/;
82     NC -= ValNo;                      // Convert from index into count
83     if (NC == 0) continue;            // Skip empty type planes...
84
85     // Output type header: [num entries][type id number]
86     //
87     output_vbr(NC, Out);
88
89     // Output the Type ID Number...
90     int Slot = Table.getValSlot(Plane.front()->getType());
91     assert (Slot != -1 && "Type in constant pool but not in function!!");
92     output_vbr((unsigned)Slot, Out);
93
94     //cerr << "Emitting " << NC << " constants of type '" 
95     //   << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
96
97     for (unsigned i = ValNo; i < ValNo+NC; ++i) {
98       const Value *V = Plane[i];
99       if (const Constant *CPV = dyn_cast<Constant>(V)) {
100         //cerr << "Serializing value: <" << V->getType() << ">: " << V << ":" 
101         //     << Out.size() << "\n";
102         outputConstant(CPV);
103       } else {
104         outputType(cast<const Type>(V));
105       }
106     }
107   }
108 }
109
110 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
111   BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
112   
113   // Output the types for the global variables in the module...
114   for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
115     const GlobalVariable *GV = *I;
116     int Slot = Table.getValSlot(GV->getType());
117     assert(Slot != -1 && "Module global vars is broken!");
118
119     // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2=InternalLinkage,
120     // bit3+ = slot#
121     unsigned oSlot = ((unsigned)Slot << 3) | (GV->hasInternalLinkage() << 2) |
122                      (GV->hasInitializer() << 1) | GV->isConstant();
123     output_vbr(oSlot, Out);
124
125     // If we have an initializer, output it now.
126     if (GV->hasInitializer()) {
127       Slot = Table.getValSlot((Value*)GV->getInitializer());
128       assert(Slot != -1 && "No slot for global var initializer!");
129       output_vbr((unsigned)Slot, Out);
130     }
131   }
132   output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
133
134   // Output the types of the functions in this module...
135   for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
136     int Slot = Table.getValSlot((*I)->getType());
137     assert(Slot != -1 && "Module const pool is broken!");
138     assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
139     output_vbr((unsigned)Slot, Out);
140   }
141   output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
142
143
144   align32(Out);
145 }
146
147 void BytecodeWriter::processMethod(const Function *M) {
148   BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
149   output_vbr((unsigned)M->hasInternalLinkage(), Out);
150   // Only output the constant pool and other goodies if needed...
151   if (!M->isExternal()) {
152
153     // Get slot information about the function...
154     Table.incorporateFunction(M);
155
156     // Output information about the constants in the function...
157     outputConstants(true);
158
159     // Output basic block nodes...
160     for_each(M->begin(), M->end(),
161              bind_obj(this, &BytecodeWriter::processBasicBlock));
162     
163     // If needed, output the symbol table for the function...
164     if (M->hasSymbolTable())
165       outputSymbolTable(*M->getSymbolTable());
166     
167     Table.purgeFunction();
168   }
169 }
170
171
172 void BytecodeWriter::processBasicBlock(const BasicBlock *BB) {
173   BytecodeBlock FunctionBlock(BytecodeFormat::BasicBlock, Out);
174   // Process all the instructions in the bb...
175   for_each(BB->begin(), BB->end(),
176            bind_obj(this, &BytecodeWriter::processInstruction));
177 }
178
179 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
180   BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
181
182   for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
183     SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
184     SymbolTable::type_const_iterator End = MST.type_end(TI->first);
185     int Slot;
186     
187     if (I == End) continue;  // Don't mess with an absent type...
188
189     // Symtab block header: [num entries][type id number]
190     output_vbr(MST.type_size(TI->first), Out);
191
192     Slot = Table.getValSlot(TI->first);
193     assert(Slot != -1 && "Type in symtab, but not in table!");
194     output_vbr((unsigned)Slot, Out);
195
196     for (; I != End; ++I) {
197       // Symtab entry: [def slot #][name]
198       Slot = Table.getValSlot(I->second);
199       assert(Slot != -1 && "Value in symtab but has no slot number!!");
200       output_vbr((unsigned)Slot, Out);
201       output(I->first, Out, false); // Don't force alignment...
202     }
203   }
204 }
205
206 void WriteBytecodeToFile(const Module *C, ostream &Out) {
207   assert(C && "You can't write a null module!!");
208
209   std::deque<unsigned char> Buffer;
210
211   // This object populates buffer for us...
212   BytecodeWriter BCW(Buffer, C);
213
214   // Okay, write the deque out to the ostream now... the deque is not
215   // sequential in memory, however, so write out as much as possible in big
216   // chunks, until we're done.
217   //
218   std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
219   while (I != E) {                           // Loop until it's all written
220     // Scan to see how big this chunk is...
221     const unsigned char *ChunkPtr = &*I;
222     const unsigned char *LastPtr = ChunkPtr;
223     while (I != E) {
224       const unsigned char *ThisPtr = &*++I;
225       if (LastPtr+1 != ThisPtr) {   // Advanced by more than a byte of memory?
226         ++LastPtr;
227         break;
228       }
229       LastPtr = ThisPtr;
230     }
231     
232     // Write out the chunk...
233     Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);
234   }
235
236   Out.flush();
237 }