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"
41 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
44 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
47 BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M)
48 : Out(o), Table(M, false) {
52 // Emit the top level CLASS block.
53 BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
55 bool isBigEndian = M->getEndianness() == Module::BigEndian;
56 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
57 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
58 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
60 // Output the version identifier... we are currently on bytecode version #0
61 unsigned Version = (0 << 4) | isBigEndian | (hasLongPointers << 1) |
62 (hasNoEndianness << 2) | (hasNoPointerSize << 3);
63 output_vbr(Version, Out);
67 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out);
69 // Write the type plane for types first because earlier planes (e.g. for a
70 // primitive type like float) may have constants constructed using types
71 // coming later (e.g., via getelementptr from a pointer type). The type
72 // plane is needed before types can be fwd or bkwd referenced.
73 const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
74 assert(!Plane.empty() && "No types at all?");
75 unsigned ValNo = Type::FirstDerivedTyID; // Start at the derived types...
76 outputConstantsInPlane(Plane, ValNo); // Write out the types
79 // The ModuleInfoBlock follows directly after the type information
80 outputModuleInfoBlock(M);
82 // Output module level constants, used for global variable initializers
83 outputConstants(false);
85 // Do the whole module now! Process each function at a time...
86 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
89 // If needed, output the symbol table for the module...
90 outputSymbolTable(M->getSymbolTable());
93 // Helper function for outputConstants().
94 // Writes out all the constants in the plane Plane starting at entry StartNo.
96 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
97 &Plane, unsigned StartNo) {
98 unsigned ValNo = StartNo;
100 // Scan through and ignore function arguments/global values...
101 for (; ValNo < Plane.size() && (isa<Argument>(Plane[ValNo]) ||
102 isa<GlobalValue>(Plane[ValNo])); ValNo++)
105 unsigned NC = ValNo; // Number of constants
106 for (; NC < Plane.size() &&
107 (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
109 NC -= ValNo; // Convert from index into count
110 if (NC == 0) return; // Skip empty type planes...
112 // Output type header: [num entries][type id number]
116 // Output the Type ID Number...
117 int Slot = Table.getSlot(Plane.front()->getType());
118 assert (Slot != -1 && "Type in constant pool but not in function!!");
119 output_vbr((unsigned)Slot, Out);
121 //cerr << "Emitting " << NC << " constants of type '"
122 // << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
124 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
125 const Value *V = Plane[i];
126 if (const Constant *CPV = dyn_cast<Constant>(V)) {
127 //cerr << "Serializing value: <" << V->getType() << ">: " << V << ":"
128 // << Out.size() << "\n";
131 outputType(cast<Type>(V));
136 void BytecodeWriter::outputConstants(bool isFunction) {
137 BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
139 unsigned NumPlanes = Table.getNumPlanes();
141 // Output the type plane before any constants!
142 if (isFunction && NumPlanes > Type::TypeTyID) {
143 const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
144 if (!Plane.empty()) { // Skip empty type planes...
145 unsigned ValNo = Table.getModuleLevel(Type::TypeTyID);
146 outputConstantsInPlane(Plane, ValNo);
150 for (unsigned pno = 0; pno != NumPlanes; pno++)
151 if (pno != Type::TypeTyID) { // Type plane handled above.
152 const std::vector<const Value*> &Plane = Table.getPlane(pno);
153 if (!Plane.empty()) { // Skip empty type planes...
155 if (isFunction) // Don't re-emit module constants
156 ValNo += Table.getModuleLevel(pno);
158 if (pno >= Type::FirstDerivedTyID) {
159 // Skip zero initializer
164 // Write out constants in the plane
165 outputConstantsInPlane(Plane, ValNo);
170 static unsigned getEncodedLinkage(const GlobalValue *GV) {
171 switch (GV->getLinkage()) {
172 default: assert(0 && "Invalid linkage!");
173 case GlobalValue::ExternalLinkage: return 0;
174 case GlobalValue::WeakLinkage: return 1;
175 case GlobalValue::AppendingLinkage: return 2;
176 case GlobalValue::InternalLinkage: return 3;
177 case GlobalValue::LinkOnceLinkage: return 4;
181 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
182 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
184 // Output the types for the global variables in the module...
185 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
186 int Slot = Table.getSlot(I->getType());
187 assert(Slot != -1 && "Module global vars is broken!");
189 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
190 // bit5+ = Slot # for type
191 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
192 (I->hasInitializer() << 1) | I->isConstant();
193 output_vbr(oSlot, Out);
195 // If we have an initializer, output it now.
196 if (I->hasInitializer()) {
197 Slot = Table.getSlot((Value*)I->getInitializer());
198 assert(Slot != -1 && "No slot for global var initializer!");
199 output_vbr((unsigned)Slot, Out);
202 output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
204 // Output the types of the functions in this module...
205 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
206 int Slot = Table.getSlot(I->getType());
207 assert(Slot != -1 && "Module const pool is broken!");
208 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
209 output_vbr((unsigned)Slot, Out);
211 output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
216 void BytecodeWriter::outputFunction(const Function *F) {
217 BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
218 output_vbr(getEncodedLinkage(F), Out);
219 // Only output the constant pool and other goodies if needed...
220 if (!F->isExternal()) {
222 // Get slot information about the function...
223 Table.incorporateFunction(F);
225 // Output information about the constants in the function...
226 outputConstants(true);
228 // Output basic block nodes...
229 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
230 processBasicBlock(*I);
232 // If needed, output the symbol table for the function...
233 outputSymbolTable(F->getSymbolTable());
235 Table.purgeFunction();
240 void BytecodeWriter::processBasicBlock(const BasicBlock &BB) {
241 BytecodeBlock FunctionBlock(BytecodeFormat::BasicBlock, Out);
242 // Process all the instructions in the bb...
243 for(BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I)
244 processInstruction(*I);
247 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
248 BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out);
250 for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
251 SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
252 SymbolTable::type_const_iterator End = MST.type_end(TI->first);
255 if (I == End) continue; // Don't mess with an absent type...
257 // Symtab block header: [num entries][type id number]
258 output_vbr(MST.type_size(TI->first), Out);
260 Slot = Table.getSlot(TI->first);
261 assert(Slot != -1 && "Type in symtab, but not in table!");
262 output_vbr((unsigned)Slot, Out);
264 for (; I != End; ++I) {
265 // Symtab entry: [def slot #][name]
266 Slot = Table.getSlot(I->second);
267 assert(Slot != -1 && "Value in symtab but has no slot number!!");
268 output_vbr((unsigned)Slot, Out);
269 output(I->first, Out, false); // Don't force alignment...
274 void WriteBytecodeToFile(const Module *C, std::ostream &Out) {
275 assert(C && "You can't write a null module!!");
277 std::deque<unsigned char> Buffer;
279 // This object populates buffer for us...
280 BytecodeWriter BCW(Buffer, C);
282 // Keep track of how much we've written...
283 BytesWritten += Buffer.size();
285 // Okay, write the deque out to the ostream now... the deque is not
286 // sequential in memory, however, so write out as much as possible in big
287 // chunks, until we're done.
289 std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
290 while (I != E) { // Loop until it's all written
291 // Scan to see how big this chunk is...
292 const unsigned char *ChunkPtr = &*I;
293 const unsigned char *LastPtr = ChunkPtr;
295 const unsigned char *ThisPtr = &*++I;
296 if (LastPtr+1 != ThisPtr) { // Advanced by more than a byte of memory?
303 // Write out the chunk...
304 Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);
310 } // End llvm namespace