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/Module.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Function.h"
26 #include "llvm/BasicBlock.h"
27 #include "llvm/ConstantVals.h"
28 #include "llvm/SymbolTable.h"
29 #include "llvm/DerivedTypes.h"
30 #include "Support/STLExtras.h"
34 BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M)
35 : Out(o), Table(M, false) {
39 // Emit the top level CLASS block.
40 BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
42 // Output the ID of first "derived" type:
43 output_vbr((unsigned)Type::FirstDerivedTyID, Out);
46 // Output module level constants, including types used by the function protos
47 outputConstants(false);
49 // The ModuleInfoBlock follows directly after the Module constant pool
50 outputModuleInfoBlock(M);
52 // Do the whole module now! Process each function at a time...
53 for_each(M->begin(), M->end(),
54 bind_obj(this, &BytecodeWriter::processMethod));
56 // If needed, output the symbol table for the module...
57 if (M->hasSymbolTable())
58 outputSymbolTable(*M->getSymbolTable());
61 void BytecodeWriter::outputConstants(bool isFunction) {
62 BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
64 unsigned NumPlanes = Table.getNumPlanes();
65 for (unsigned pno = 0; pno < NumPlanes; pno++) {
66 const std::vector<const Value*> &Plane = Table.getPlane(pno);
67 if (Plane.empty()) continue; // Skip empty type planes...
70 if (isFunction) // Don't reemit module constants
71 ValNo = Table.getModuleLevel(pno);
72 else if (pno == Type::TypeTyID)
73 ValNo = Type::FirstDerivedTyID; // Start emitting at the derived types...
75 // Scan through and ignore function arguments...
76 for (; ValNo < Plane.size() && isa<FunctionArgument>(Plane[ValNo]); ValNo++)
79 unsigned NC = ValNo; // Number of constants
80 for (; NC < Plane.size() &&
81 (isa<Constant>(Plane[NC]) ||
82 isa<Type>(Plane[NC])); NC++) /*empty*/;
83 NC -= ValNo; // Convert from index into count
84 if (NC == 0) continue; // Skip empty type planes...
86 // Output type header: [num entries][type id number]
90 // Output the Type ID Number...
91 int Slot = Table.getValSlot(Plane.front()->getType());
92 assert (Slot != -1 && "Type in constant pool but not in function!!");
93 output_vbr((unsigned)Slot, Out);
95 //cerr << "Emitting " << NC << " constants of type '"
96 // << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
98 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
99 const Value *V = Plane[i];
100 if (const Constant *CPV = dyn_cast<Constant>(V)) {
101 //cerr << "Serializing value: <" << V->getType() << ">: "
102 // << ((const Constant*)V)->getStrValue() << ":"
103 // << Out.size() << "\n";
106 outputType(cast<const Type>(V));
112 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
113 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
115 // Output the types for the global variables in the module...
116 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
117 const GlobalVariable *GV = *I;
118 int Slot = Table.getValSlot(GV->getType());
119 assert(Slot != -1 && "Module global vars is broken!");
121 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2=InternalLinkage,
123 unsigned oSlot = ((unsigned)Slot << 3) | (GV->hasInternalLinkage() << 2) |
124 (GV->hasInitializer() << 1) | GV->isConstant();
125 output_vbr(oSlot, Out);
127 // If we have an initializer, output it now.
128 if (GV->hasInitializer()) {
129 Slot = Table.getValSlot(GV->getInitializer());
130 assert(Slot != -1 && "No slot for global var initializer!");
131 output_vbr((unsigned)Slot, Out);
134 output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
136 // Output the types of the functions in this module...
137 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
138 int Slot = Table.getValSlot((*I)->getType());
139 assert(Slot != -1 && "Module const pool is broken!");
140 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
141 output_vbr((unsigned)Slot, Out);
143 output_vbr((unsigned)Table.getValSlot(Type::VoidTy), Out);
149 void BytecodeWriter::processMethod(const Function *M) {
150 BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
151 output_vbr((unsigned)M->hasInternalLinkage(), Out);
152 // Only output the constant pool and other goodies if needed...
153 if (!M->isExternal()) {
155 // Get slot information about the function...
156 Table.incorporateFunction(M);
158 // Output information about the constants in the function...
159 outputConstants(true);
161 // Output basic block nodes...
162 for_each(M->begin(), M->end(),
163 bind_obj(this, &BytecodeWriter::processBasicBlock));
165 // If needed, output the symbol table for the function...
166 if (M->hasSymbolTable())
167 outputSymbolTable(*M->getSymbolTable());
169 Table.purgeFunction();
174 void BytecodeWriter::processBasicBlock(const BasicBlock *BB) {
175 BytecodeBlock FunctionBlock(BytecodeFormat::BasicBlock, Out);
176 // Process all the instructions in the bb...
177 for_each(BB->begin(), BB->end(),
178 bind_obj(this, &BytecodeWriter::processInstruction));
181 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
182 BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
184 for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
185 SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
186 SymbolTable::type_const_iterator End = MST.type_end(TI->first);
189 if (I == End) continue; // Don't mess with an absent type...
191 // Symtab block header: [num entries][type id number]
192 output_vbr(MST.type_size(TI->first), Out);
194 Slot = Table.getValSlot(TI->first);
195 assert(Slot != -1 && "Type in symtab, but not in table!");
196 output_vbr((unsigned)Slot, Out);
198 for (; I != End; ++I) {
199 // Symtab entry: [def slot #][name]
200 Slot = Table.getValSlot(I->second);
201 assert(Slot != -1 && "Value in symtab but has no slot number!!");
202 output_vbr((unsigned)Slot, Out);
203 output(I->first, Out, false); // Don't force alignment...
208 void WriteBytecodeToFile(const Module *C, ostream &Out) {
209 assert(C && "You can't write a null module!!");
211 std::deque<unsigned char> Buffer;
213 // This object populates buffer for us...
214 BytecodeWriter BCW(Buffer, C);
216 // Okay, write the deque out to the ostream now... the deque is not
217 // sequential in memory, however, so write out as much as possible in big
218 // chunks, until we're done.
220 std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
221 while (I != E) { // Loop until it's all written
222 // Scan to see how big this chunk is...
223 const unsigned char *ChunkPtr = &*I;
224 const unsigned char *LastPtr = ChunkPtr;
226 const unsigned char *ThisPtr = &*++I;
227 if (LastPtr+1 != ThisPtr) { // Advanced by more than a byte of memory?
234 // Write out the chunk...
235 Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);