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