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 bool isBigEndian = M->isBigEndian();
47 bool hasLongPointers = M->has64BitPointers();
49 // Output the version identifier... we are currently on bytecode version #2
50 unsigned Version = (2 << 4) | isBigEndian | (hasLongPointers << 1);
51 output_vbr(Version, Out);
55 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out);
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
67 // The ModuleInfoBlock follows directly after the type information
68 outputModuleInfoBlock(M);
70 // Output module level constants, used for global variable initializers
71 outputConstants(false);
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)
77 // If needed, output the symbol table for the module...
78 outputSymbolTable(M->getSymbolTable());
81 // Helper function for outputConstants().
82 // Writes out all the constants in the plane Plane starting at entry StartNo.
84 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
85 &Plane, unsigned StartNo) {
86 unsigned ValNo = StartNo;
88 // Scan through and ignore function arguments/global values...
89 for (; ValNo < Plane.size() && (isa<Argument>(Plane[ValNo]) ||
90 isa<GlobalValue>(Plane[ValNo])); ValNo++)
93 unsigned NC = ValNo; // Number of constants
94 for (; NC < Plane.size() &&
95 (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
97 NC -= ValNo; // Convert from index into count
98 if (NC == 0) return; // Skip empty type planes...
100 // Output type header: [num entries][type id number]
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);
109 //cerr << "Emitting " << NC << " constants of type '"
110 // << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
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";
119 outputType(cast<Type>(V));
124 void BytecodeWriter::outputConstants(bool isFunction) {
125 BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
127 unsigned NumPlanes = Table.getNumPlanes();
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...
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
138 if (pno >= Type::FirstDerivedTyID) {
139 // Skip zero initializer
144 outputConstantsInPlane(Plane, ValNo); // Write out constants in the plane
149 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
150 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
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!");
157 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3=Linkage,
158 // bit4+ = Slot # for type
159 unsigned oSlot = ((unsigned)Slot << 4) | ((unsigned)I->getLinkage() << 2) |
160 (I->hasInitializer() << 1) | I->isConstant();
161 output_vbr(oSlot, Out);
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);
170 output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
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);
179 output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
184 void BytecodeWriter::outputFunction(const Function *F) {
185 BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
186 output_vbr((unsigned)F->getLinkage(), Out);
187 // Only output the constant pool and other goodies if needed...
188 if (!F->isExternal()) {
190 // Get slot information about the function...
191 Table.incorporateFunction(F);
193 // Output information about the constants in the function...
194 outputConstants(true);
196 // Output basic block nodes...
197 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
198 processBasicBlock(*I);
200 // If needed, output the symbol table for the function...
201 outputSymbolTable(F->getSymbolTable());
203 Table.purgeFunction();
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);
215 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
216 BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
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);
223 if (I == End) continue; // Don't mess with an absent type...
225 // Symtab block header: [num entries][type id number]
226 output_vbr(MST.type_size(TI->first), Out);
228 Slot = Table.getValSlot(TI->first);
229 assert(Slot != -1 && "Type in symtab, but not in table!");
230 output_vbr((unsigned)Slot, Out);
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...
242 void WriteBytecodeToFile(const Module *C, std::ostream &Out) {
243 assert(C && "You can't write a null module!!");
245 std::deque<unsigned char> Buffer;
247 // This object populates buffer for us...
248 BytecodeWriter BCW(Buffer, C);
250 // Keep track of how much we've written...
251 BytesWritten += Buffer.size();
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.
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;
263 const unsigned char *ThisPtr = &*++I;
264 if (LastPtr+1 != ThisPtr) { // Advanced by more than a byte of memory?
271 // Write out the chunk...
272 Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);