*** empty log message ***
[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/Bytecode/WriteBytecodePass.h"
24 #include "llvm/Module.h"
25 #include "llvm/SymbolTable.h"
26 #include "llvm/DerivedTypes.h"
27 #include "Support/STLExtras.h"
28 #include "Support/StatisticReporter.h"
29 #include <string.h>
30 #include <algorithm>
31
32 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
33
34 static Statistic<> 
35 BytesWritten("bytecodewriter\t- Number of bytecode bytes written");
36
37
38 BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M) 
39   : Out(o), Table(M, false) {
40
41   outputSignature();
42
43   // Emit the top level CLASS block.
44   BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
45
46   // Output the ID of first "derived" type:
47   output_vbr((unsigned)Type::FirstDerivedTyID, Out);
48   align32(Out);
49
50   // Output module level constants, including types used by the function protos
51   outputConstants(false);
52
53   // The ModuleInfoBlock follows directly after the Module constant pool
54   outputModuleInfoBlock(M);
55
56   // Do the whole module now! Process each function at a time...
57   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
58     processMethod(I);
59
60   // If needed, output the symbol table for the module...
61   if (M->hasSymbolTable())
62     outputSymbolTable(*M->getSymbolTable());
63 }
64
65 // Helper function for outputConstants().
66 // Writes out all the constants in the plane Plane starting at entry StartNo.
67 // 
68 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
69                                             &Plane, unsigned StartNo) {
70   unsigned ValNo = StartNo;
71   
72   // Scan through and ignore function arguments...
73   for (; ValNo < Plane.size() && isa<Argument>(Plane[ValNo]); ValNo++)
74     /*empty*/;
75
76   unsigned NC = ValNo;              // Number of constants
77   for (; NC < Plane.size() && 
78          (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
79     /*empty*/;
80   NC -= ValNo;                      // Convert from index into count
81   if (NC == 0) return;              // Skip empty type planes...
82
83   // Output type header: [num entries][type id number]
84   //
85   output_vbr(NC, Out);
86
87   // Output the Type ID Number...
88   int Slot = Table.getValSlot(Plane.front()->getType());
89   assert (Slot != -1 && "Type in constant pool but not in function!!");
90   output_vbr((unsigned)Slot, Out);
91
92   //cerr << "Emitting " << NC << " constants of type '" 
93   //     << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
94
95   for (unsigned i = ValNo; i < ValNo+NC; ++i) {
96     const Value *V = Plane[i];
97     if (const Constant *CPV = dyn_cast<Constant>(V)) {
98       //cerr << "Serializing value: <" << V->getType() << ">: " << V << ":" 
99       //     << Out.size() << "\n";
100       outputConstant(CPV);
101     } else {
102       outputType(cast<const Type>(V));
103     }
104   }
105 }
106
107 void BytecodeWriter::outputConstants(bool isFunction) {
108   BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
109
110   unsigned NumPlanes = Table.getNumPlanes();
111   
112   // Write the type plane for types first because earlier planes
113   // (e.g. for a primitive type like float) may have constants constructed
114   // using types coming later (e.g., via getelementptr from a pointer type).
115   // The type plane is needed before types can be fwd or bkwd referenced.
116   if (!isFunction) {
117     const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
118     assert(!Plane.empty() && "No types at all?");
119     unsigned ValNo = Type::FirstDerivedTyID; // Start at the derived types...
120     outputConstantsInPlane(Plane, ValNo);      // Write out the types
121   }
122   
123   for (unsigned pno = 0; pno < NumPlanes; pno++) {
124     const std::vector<const Value*> &Plane = Table.getPlane(pno);
125     if (Plane.empty()) continue;      // Skip empty type planes...
126     
127     unsigned ValNo = 0;
128     if (isFunction)                   // Don't reemit module constants
129       ValNo = Table.getModuleLevel(pno);
130     else if (pno == Type::TypeTyID)
131       continue;                       // Type plane was written out above
132     
133     outputConstantsInPlane(Plane, ValNo); // Write out constants in the plane
134   }
135 }
136
137 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
138   BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
139   
140   // Output the types for the global variables in the module...
141   for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
142     int Slot = Table.getValSlot(I->getType());
143     assert(Slot != -1 && "Module global vars is broken!");
144
145     // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2=InternalLinkage,
146     // bit3+ = slot#
147     unsigned oSlot = ((unsigned)Slot << 3) | (I->hasInternalLinkage() << 2) |
148                      (I->hasInitializer() << 1) | I->isConstant();
149     output_vbr(oSlot, Out);
150
151     // If we have an initializer, output it now.
152     if (I->hasInitializer()) {
153       Slot = Table.getValSlot((Value*)I->getInitializer());
154       assert(Slot != -1 && "No slot for global var initializer!");
155       output_vbr((unsigned)Slot, Out);
156     }
157   }
158   output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
159
160   // Output the types of the functions in this module...
161   for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
162     int Slot = Table.getValSlot(I->getType());
163     assert(Slot != -1 && "Module const pool is broken!");
164     assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
165     output_vbr((unsigned)Slot, Out);
166   }
167   output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
168
169
170   align32(Out);
171 }
172
173 void BytecodeWriter::processMethod(const Function *F) {
174   BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
175   output_vbr((unsigned)F->hasInternalLinkage(), Out);
176   // Only output the constant pool and other goodies if needed...
177   if (!F->isExternal()) {
178
179     // Get slot information about the function...
180     Table.incorporateFunction(F);
181
182     // Output information about the constants in the function...
183     outputConstants(true);
184
185     // Output basic block nodes...
186     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
187       processBasicBlock(*I);
188     
189     // If needed, output the symbol table for the function...
190     if (F->hasSymbolTable())
191       outputSymbolTable(*F->getSymbolTable());
192     
193     Table.purgeFunction();
194   }
195 }
196
197
198 void BytecodeWriter::processBasicBlock(const BasicBlock &BB) {
199   BytecodeBlock FunctionBlock(BytecodeFormat::BasicBlock, Out);
200   // Process all the instructions in the bb...
201   for(BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I)
202     processInstruction(*I);
203 }
204
205 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
206   BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
207
208   for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
209     SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
210     SymbolTable::type_const_iterator End = MST.type_end(TI->first);
211     int Slot;
212     
213     if (I == End) continue;  // Don't mess with an absent type...
214
215     // Symtab block header: [num entries][type id number]
216     output_vbr(MST.type_size(TI->first), Out);
217
218     Slot = Table.getValSlot(TI->first);
219     assert(Slot != -1 && "Type in symtab, but not in table!");
220     output_vbr((unsigned)Slot, Out);
221
222     for (; I != End; ++I) {
223       // Symtab entry: [def slot #][name]
224       Slot = Table.getValSlot(I->second);
225       assert(Slot != -1 && "Value in symtab but has no slot number!!");
226       output_vbr((unsigned)Slot, Out);
227       output(I->first, Out, false); // Don't force alignment...
228     }
229   }
230 }
231
232 void WriteBytecodeToFile(const Module *C, std::ostream &Out) {
233   assert(C && "You can't write a null module!!");
234
235   std::deque<unsigned char> Buffer;
236
237   // This object populates buffer for us...
238   BytecodeWriter BCW(Buffer, C);
239
240   // Keep track of how much we've written...
241   BytesWritten += Buffer.size();
242
243   // Okay, write the deque out to the ostream now... the deque is not
244   // sequential in memory, however, so write out as much as possible in big
245   // chunks, until we're done.
246   //
247   std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
248   while (I != E) {                           // Loop until it's all written
249     // Scan to see how big this chunk is...
250     const unsigned char *ChunkPtr = &*I;
251     const unsigned char *LastPtr = ChunkPtr;
252     while (I != E) {
253       const unsigned char *ThisPtr = &*++I;
254       if (LastPtr+1 != ThisPtr) {   // Advanced by more than a byte of memory?
255         ++LastPtr;
256         break;
257       }
258       LastPtr = ThisPtr;
259     }
260     
261     // Write out the chunk...
262     Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);
263   }
264
265   Out.flush();
266 }