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