1 //===-- Writer.cpp - Library for writing VM bytecode files -------*- C++ -*--=//
3 // This library implements the functionality defined in llvm/Bytecode/Writer.h
5 // This library uses the Analysis library to figure out offsets for
6 // variables in the method tables...
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. :( :( :(
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.
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
23 //===----------------------------------------------------------------------===//
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"
37 BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M)
38 : Out(o), Table(M, false) {
42 // Emit the top level CLASS block.
43 BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
45 // Output the ID of first "derived" type:
46 output_vbr((unsigned)Type::FirstDerivedTyID, Out);
49 // Output module level constants, including types used by the method protos
50 outputConstants(false);
52 // The ModuleInfoBlock follows directly after the Module constant pool
53 outputModuleInfoBlock(M);
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));
59 // If needed, output the symbol table for the module...
60 if (M->hasSymbolTable())
61 outputSymbolTable(*M->getSymbolTable());
64 void BytecodeWriter::outputConstants(bool isFunction) {
65 BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
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...
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...
78 // Scan through and ignore method arguments...
79 for (; ValNo < Plane.size() && isa<FunctionArgument>(Plane[ValNo]); ValNo++)
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...
89 // Output type header: [num entries][type id number]
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);
98 //cerr << "Emitting " << NC << " constants of type '"
99 // << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
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";
109 outputType(cast<const Type>(V));
115 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
116 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
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!");
124 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2=InternalLinkage,
126 unsigned oSlot = ((unsigned)Slot << 3) | (GV->hasInternalLinkage() << 2) |
127 (GV->hasInitializer() << 1) | GV->isConstant();
128 output_vbr(oSlot, Out);
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);
137 output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
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);
146 output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
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()) {
158 // Get slot information about the method...
159 Table.incorporateMethod(M);
161 // Output information about the constants in the method...
162 outputConstants(true);
164 // Output basic block nodes...
165 for_each(M->begin(), M->end(),
166 bind_obj(this, &BytecodeWriter::processBasicBlock));
168 // If needed, output the symbol table for the method...
169 if (M->hasSymbolTable())
170 outputSymbolTable(*M->getSymbolTable());
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));
184 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
185 BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
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);
192 if (I == End) continue; // Don't mess with an absent type...
194 // Symtab block header: [num entries][type id number]
195 output_vbr(MST.type_size(TI->first), Out);
197 Slot = Table.getValSlot(TI->first);
198 assert(Slot != -1 && "Type in symtab, but not in table!");
199 output_vbr((unsigned)Slot, Out);
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...
211 void WriteBytecodeToFile(const Module *C, ostream &Out) {
212 assert(C && "You can't write a null module!!");
214 std::deque<unsigned char> Buffer;
216 // This object populates buffer for us...
217 BytecodeWriter BCW(Buffer, C);
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.
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;
229 const unsigned char *ThisPtr = &*++I;
230 if (LastPtr+1 != ThisPtr) { // Advanced by more than a byte of memory?
237 // Write out the chunk...
238 Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);