1 //===-- Writer.cpp - Library for writing VM bytecode files ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Bytecode/Writer.h
12 // Note that this file uses an unusual technique of outputting all the bytecode
13 // to a deque of unsigned char, then copies the deque to an ostream. The
14 // reason for this is that we must do "seeking" in the stream to do back-
15 // patching, and some very important ostreams that we want to support (like
16 // pipes) do not support seeking. :( :( :(
18 // The choice of the deque data structure is influenced by the extremely fast
19 // "append" speed, plus the free "seek"/replace in the middle of the stream. I
20 // didn't use a vector because the stream could end up very large and copying
21 // the whole thing to reallocate would be kinda silly.
23 // Note that the performance of this library is not terribly important, because
24 // it shouldn't be used by JIT type applications... so it is not a huge focus
27 //===----------------------------------------------------------------------===//
29 #include "WriterInternals.h"
30 #include "llvm/Bytecode/WriteBytecodePass.h"
31 #include "llvm/Module.h"
32 #include "llvm/SymbolTable.h"
33 #include "llvm/DerivedTypes.h"
34 #include "Support/STLExtras.h"
35 #include "Support/Statistic.h"
36 #include "Config/string.h"
39 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
42 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
45 BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M)
46 : Out(o), Table(M, false) {
50 // Emit the top level CLASS block.
51 BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
53 bool isBigEndian = M->getEndianness() == Module::BigEndian;
54 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
55 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
56 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
58 // Output the version identifier... we are currently on bytecode version #0
59 unsigned Version = (0 << 4) | isBigEndian | (hasLongPointers << 1) |
60 (hasNoEndianness << 2) | (hasNoPointerSize << 3);
61 output_vbr(Version, Out);
65 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out);
67 // Write the type plane for types first because earlier planes (e.g. for a
68 // primitive type like float) may have constants constructed using types
69 // coming later (e.g., via getelementptr from a pointer type). The type
70 // plane is needed before types can be fwd or bkwd referenced.
71 const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
72 assert(!Plane.empty() && "No types at all?");
73 unsigned ValNo = Type::FirstDerivedTyID; // Start at the derived types...
74 outputConstantsInPlane(Plane, ValNo); // Write out the types
77 // The ModuleInfoBlock follows directly after the type information
78 outputModuleInfoBlock(M);
80 // Output module level constants, used for global variable initializers
81 outputConstants(false);
83 // Do the whole module now! Process each function at a time...
84 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
87 // If needed, output the symbol table for the module...
88 outputSymbolTable(M->getSymbolTable());
91 // Helper function for outputConstants().
92 // Writes out all the constants in the plane Plane starting at entry StartNo.
94 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
95 &Plane, unsigned StartNo) {
96 unsigned ValNo = StartNo;
98 // Scan through and ignore function arguments/global values...
99 for (; ValNo < Plane.size() && (isa<Argument>(Plane[ValNo]) ||
100 isa<GlobalValue>(Plane[ValNo])); ValNo++)
103 unsigned NC = ValNo; // Number of constants
104 for (; NC < Plane.size() &&
105 (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
107 NC -= ValNo; // Convert from index into count
108 if (NC == 0) return; // Skip empty type planes...
110 // Output type header: [num entries][type id number]
114 // Output the Type ID Number...
115 int Slot = Table.getSlot(Plane.front()->getType());
116 assert (Slot != -1 && "Type in constant pool but not in function!!");
117 output_vbr((unsigned)Slot, Out);
119 //cerr << "Emitting " << NC << " constants of type '"
120 // << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
122 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
123 const Value *V = Plane[i];
124 if (const Constant *CPV = dyn_cast<Constant>(V)) {
125 //cerr << "Serializing value: <" << V->getType() << ">: " << V << ":"
126 // << Out.size() << "\n";
129 outputType(cast<Type>(V));
134 void BytecodeWriter::outputConstants(bool isFunction) {
135 BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
137 unsigned NumPlanes = Table.getNumPlanes();
139 // Output the type plane before any constants!
140 if (isFunction && NumPlanes > Type::TypeTyID) {
141 const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
142 if (!Plane.empty()) { // Skip empty type planes...
143 unsigned ValNo = Table.getModuleLevel(Type::TypeTyID);
144 outputConstantsInPlane(Plane, ValNo);
148 for (unsigned pno = 0; pno != NumPlanes; pno++)
149 if (pno != Type::TypeTyID) { // Type plane handled above.
150 const std::vector<const Value*> &Plane = Table.getPlane(pno);
151 if (!Plane.empty()) { // Skip empty type planes...
153 if (isFunction) // Don't re-emit module constants
154 ValNo += Table.getModuleLevel(pno);
156 if (pno >= Type::FirstDerivedTyID) {
157 // Skip zero initializer
162 // Write out constants in the plane
163 outputConstantsInPlane(Plane, ValNo);
168 static unsigned getEncodedLinkage(const GlobalValue *GV) {
169 switch (GV->getLinkage()) {
170 default: assert(0 && "Invalid linkage!");
171 case GlobalValue::ExternalLinkage: return 0;
172 case GlobalValue::WeakLinkage: return 1;
173 case GlobalValue::AppendingLinkage: return 2;
174 case GlobalValue::InternalLinkage: return 3;
175 case GlobalValue::LinkOnceLinkage: return 4;
179 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
180 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
182 // Output the types for the global variables in the module...
183 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
184 int Slot = Table.getSlot(I->getType());
185 assert(Slot != -1 && "Module global vars is broken!");
187 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
188 // bit5+ = Slot # for type
189 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
190 (I->hasInitializer() << 1) | I->isConstant();
191 output_vbr(oSlot, Out);
193 // If we have an initializer, output it now.
194 if (I->hasInitializer()) {
195 Slot = Table.getSlot((Value*)I->getInitializer());
196 assert(Slot != -1 && "No slot for global var initializer!");
197 output_vbr((unsigned)Slot, Out);
200 output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
202 // Output the types of the functions in this module...
203 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
204 int Slot = Table.getSlot(I->getType());
205 assert(Slot != -1 && "Module const pool is broken!");
206 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
207 output_vbr((unsigned)Slot, Out);
209 output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
214 void BytecodeWriter::outputFunction(const Function *F) {
215 BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
216 output_vbr(getEncodedLinkage(F), Out);
217 // Only output the constant pool and other goodies if needed...
218 if (!F->isExternal()) {
220 // Get slot information about the function...
221 Table.incorporateFunction(F);
223 // Output information about the constants in the function...
224 outputConstants(true);
226 // Output basic block nodes...
227 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
228 processBasicBlock(*I);
230 // If needed, output the symbol table for the function...
231 outputSymbolTable(F->getSymbolTable());
233 Table.purgeFunction();
238 void BytecodeWriter::processBasicBlock(const BasicBlock &BB) {
239 BytecodeBlock FunctionBlock(BytecodeFormat::BasicBlock, Out);
240 // Process all the instructions in the bb...
241 for(BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I)
242 processInstruction(*I);
245 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
246 BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
248 for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
249 SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
250 SymbolTable::type_const_iterator End = MST.type_end(TI->first);
253 if (I == End) continue; // Don't mess with an absent type...
255 // Symtab block header: [num entries][type id number]
256 output_vbr(MST.type_size(TI->first), Out);
258 Slot = Table.getSlot(TI->first);
259 assert(Slot != -1 && "Type in symtab, but not in table!");
260 output_vbr((unsigned)Slot, Out);
262 for (; I != End; ++I) {
263 // Symtab entry: [def slot #][name]
264 Slot = Table.getSlot(I->second);
265 assert(Slot != -1 && "Value in symtab but has no slot number!!");
266 output_vbr((unsigned)Slot, Out);
267 output(I->first, Out, false); // Don't force alignment...
272 void WriteBytecodeToFile(const Module *C, std::ostream &Out) {
273 assert(C && "You can't write a null module!!");
275 std::deque<unsigned char> Buffer;
277 // This object populates buffer for us...
278 BytecodeWriter BCW(Buffer, C);
280 // Keep track of how much we've written...
281 BytesWritten += Buffer.size();
283 // Okay, write the deque out to the ostream now... the deque is not
284 // sequential in memory, however, so write out as much as possible in big
285 // chunks, until we're done.
287 std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
288 while (I != E) { // Loop until it's all written
289 // Scan to see how big this chunk is...
290 const unsigned char *ChunkPtr = &*I;
291 const unsigned char *LastPtr = ChunkPtr;
293 const unsigned char *ThisPtr = &*++I;
294 if (LastPtr+1 != ThisPtr) { // Advanced by more than a byte of memory?
301 // Write out the chunk...
302 Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);