1 //===-- Writer.cpp - Library for writing VM bytecode files -------*- C++ -*--=//
3 // This library implements the functionality defined in llvm/Bytecode/Writer.h
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. :( :( :(
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.
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
20 //===----------------------------------------------------------------------===//
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"
32 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
35 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
38 BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M)
39 : Out(o), Table(M, false) {
43 // Emit the top level CLASS block.
44 BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
46 // Output the ID of first "derived" type:
47 output_vbr((unsigned)Type::FirstDerivedTyID, Out);
50 // Output module level constants, including types used by the function protos
51 outputConstants(false);
53 // The ModuleInfoBlock follows directly after the Module constant pool
54 outputModuleInfoBlock(M);
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)
60 // If needed, output the symbol table for the module...
61 outputSymbolTable(M->getSymbolTable());
64 // Helper function for outputConstants().
65 // Writes out all the constants in the plane Plane starting at entry StartNo.
67 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
68 &Plane, unsigned StartNo) {
69 unsigned ValNo = StartNo;
71 // Scan through and ignore function arguments...
72 for (; ValNo < Plane.size() && isa<Argument>(Plane[ValNo]); ValNo++)
75 unsigned NC = ValNo; // Number of constants
76 for (; NC < Plane.size() &&
77 (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
79 NC -= ValNo; // Convert from index into count
80 if (NC == 0) return; // Skip empty type planes...
82 // Output type header: [num entries][type id number]
86 // Output the Type ID Number...
87 int Slot = Table.getValSlot(Plane.front()->getType());
88 assert (Slot != -1 && "Type in constant pool but not in function!!");
89 output_vbr((unsigned)Slot, Out);
91 //cerr << "Emitting " << NC << " constants of type '"
92 // << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
94 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
95 const Value *V = Plane[i];
96 if (const Constant *CPV = dyn_cast<Constant>(V)) {
97 //cerr << "Serializing value: <" << V->getType() << ">: " << V << ":"
98 // << Out.size() << "\n";
101 outputType(cast<const Type>(V));
106 void BytecodeWriter::outputConstants(bool isFunction) {
107 BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
109 unsigned NumPlanes = Table.getNumPlanes();
111 // Write the type plane for types first because earlier planes
112 // (e.g. for a primitive type like float) may have constants constructed
113 // using types coming later (e.g., via getelementptr from a pointer type).
114 // The type plane is needed before types can be fwd or bkwd referenced.
116 const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
117 assert(!Plane.empty() && "No types at all?");
118 unsigned ValNo = Type::FirstDerivedTyID; // Start at the derived types...
119 outputConstantsInPlane(Plane, ValNo); // Write out the types
122 for (unsigned pno = 0; pno != NumPlanes; pno++) {
123 const std::vector<const Value*> &Plane = Table.getPlane(pno);
124 if (!Plane.empty()) { // Skip empty type planes...
126 if (isFunction) // Don't reemit module constants
127 ValNo = Table.getModuleLevel(pno);
128 else if (pno == Type::TypeTyID) // If type plane wasn't written out above
131 outputConstantsInPlane(Plane, ValNo); // Write out constants in the plane
136 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
137 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
139 // Output the types for the global variables in the module...
140 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
141 int Slot = Table.getValSlot(I->getType());
142 assert(Slot != -1 && "Module global vars is broken!");
144 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2=InternalLinkage,
146 unsigned oSlot = ((unsigned)Slot << 3) | (I->hasInternalLinkage() << 2) |
147 (I->hasInitializer() << 1) | I->isConstant();
148 output_vbr(oSlot, Out);
150 // If we have an initializer, output it now.
151 if (I->hasInitializer()) {
152 Slot = Table.getValSlot((Value*)I->getInitializer());
153 assert(Slot != -1 && "No slot for global var initializer!");
154 output_vbr((unsigned)Slot, Out);
157 output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
159 // Output the types of the functions in this module...
160 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
161 int Slot = Table.getValSlot(I->getType());
162 assert(Slot != -1 && "Module const pool is broken!");
163 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
164 output_vbr((unsigned)Slot, Out);
166 output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
172 void BytecodeWriter::processMethod(const Function *F) {
173 BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
174 output_vbr((unsigned)F->hasInternalLinkage(), Out);
175 // Only output the constant pool and other goodies if needed...
176 if (!F->isExternal()) {
178 // Get slot information about the function...
179 Table.incorporateFunction(F);
181 // Output information about the constants in the function...
182 outputConstants(true);
184 // Output basic block nodes...
185 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
186 processBasicBlock(*I);
188 // If needed, output the symbol table for the function...
189 outputSymbolTable(F->getSymbolTable());
191 Table.purgeFunction();
196 void BytecodeWriter::processBasicBlock(const BasicBlock &BB) {
197 BytecodeBlock FunctionBlock(BytecodeFormat::BasicBlock, Out);
198 // Process all the instructions in the bb...
199 for(BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I)
200 processInstruction(*I);
203 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
204 BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
206 for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
207 SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
208 SymbolTable::type_const_iterator End = MST.type_end(TI->first);
211 if (I == End) continue; // Don't mess with an absent type...
213 // Symtab block header: [num entries][type id number]
214 output_vbr(MST.type_size(TI->first), Out);
216 Slot = Table.getValSlot(TI->first);
217 assert(Slot != -1 && "Type in symtab, but not in table!");
218 output_vbr((unsigned)Slot, Out);
220 for (; I != End; ++I) {
221 // Symtab entry: [def slot #][name]
222 Slot = Table.getValSlot(I->second);
223 assert(Slot != -1 && "Value in symtab but has no slot number!!");
224 output_vbr((unsigned)Slot, Out);
225 output(I->first, Out, false); // Don't force alignment...
230 void WriteBytecodeToFile(const Module *C, std::ostream &Out) {
231 assert(C && "You can't write a null module!!");
233 std::deque<unsigned char> Buffer;
235 // This object populates buffer for us...
236 BytecodeWriter BCW(Buffer, C);
238 // Keep track of how much we've written...
239 BytesWritten += Buffer.size();
241 // Okay, write the deque out to the ostream now... the deque is not
242 // sequential in memory, however, so write out as much as possible in big
243 // chunks, until we're done.
245 std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
246 while (I != E) { // Loop until it's all written
247 // Scan to see how big this chunk is...
248 const unsigned char *ChunkPtr = &*I;
249 const unsigned char *LastPtr = ChunkPtr;
251 const unsigned char *ThisPtr = &*++I;
252 if (LastPtr+1 != ThisPtr) { // Advanced by more than a byte of memory?
259 // Write out the chunk...
260 Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);