blob: ca50b5a7bd3869a9df055d1868501270cb533708 [file] [log] [blame]
Chris Lattner14999342004-01-10 19:07:06 +00001//===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Writer.h
11//
Chris Lattner00950542001-06-06 20:29:01 +000012// Note that this file uses an unusual technique of outputting all the bytecode
Chris Lattnerabe83ae2003-09-15 00:33:20 +000013// to a deque of unsigned char, then copies the deque to an ostream. The
Chris Lattner00950542001-06-06 20:29:01 +000014// 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. :( :( :(
17//
Chris Lattnere8fdde12001-09-07 16:39:41 +000018// 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.
Chris Lattner00950542001-06-06 20:29:01 +000022//
Chris Lattner00950542001-06-06 20:29:01 +000023//===----------------------------------------------------------------------===//
24
25#include "WriterInternals.h"
Chris Lattner635cd932002-07-23 19:56:44 +000026#include "llvm/Bytecode/WriteBytecodePass.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include "llvm/Module.h"
Chris Lattner00950542001-06-06 20:29:01 +000028#include "llvm/SymbolTable.h"
29#include "llvm/DerivedTypes.h"
Chris Lattnerf60dc882001-11-29 16:32:16 +000030#include "Support/STLExtras.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000031#include "Support/Statistic.h"
Chris Lattnerd6942d72004-01-14 16:54:21 +000032#include "Support/Debug.h"
Chris Lattner32abce62004-01-10 19:10:01 +000033#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000034#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000035using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000036
Chris Lattner635cd932002-07-23 19:56:44 +000037static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
38
Chris Lattnerce6ef112002-07-26 18:40:14 +000039static Statistic<>
Chris Lattnera92f6962002-10-01 22:38:41 +000040BytesWritten("bytecodewriter", "Number of bytecode bytes written");
Chris Lattnerd6942d72004-01-14 16:54:21 +000041static Statistic<>
42ConstantTotalBytes("bytecodewriter", "Bytes of constants total");
43static Statistic<>
44FunctionConstantTotalBytes("bytecodewriter", "Bytes of function constants total");
45static Statistic<>
46ConstantPlaneHeaderBytes("bytecodewriter", "Constant plane header bytes");
47static Statistic<>
48InstructionBytes("bytecodewriter", "Bytes of bytes of instructions");
49static Statistic<>
50SymTabBytes("bytecodewriter", "Bytes of symbol table");
51static Statistic<>
52ModuleInfoBytes("bytecodewriter", "Bytes of module info");
Chris Lattner635cd932002-07-23 19:56:44 +000053
Chris Lattner697954c2002-01-20 22:54:45 +000054BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M)
Chris Lattner277bafb2004-01-14 02:50:16 +000055 : Out(o), Table(M, true) {
Chris Lattner00950542001-06-06 20:29:01 +000056
57 outputSignature();
58
59 // Emit the top level CLASS block.
60 BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);
61
Chris Lattnerd445c6b2003-08-24 13:47:36 +000062 bool isBigEndian = M->getEndianness() == Module::BigEndian;
63 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
64 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
65 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner186a1f72003-03-19 20:56:46 +000066
Chris Lattnerd6942d72004-01-14 16:54:21 +000067 // Output the version identifier... we are currently on bytecode version #1,
68 // which corresponds to LLVM v1.2.
69 unsigned Version = (1 << 4) | isBigEndian | (hasLongPointers << 1) |
Chris Lattnerd445c6b2003-08-24 13:47:36 +000070 (hasNoEndianness << 2) | (hasNoPointerSize << 3);
Chris Lattner186a1f72003-03-19 20:56:46 +000071 output_vbr(Version, Out);
Chris Lattner00950542001-06-06 20:29:01 +000072 align32(Out);
73
Chris Lattner186a1f72003-03-19 20:56:46 +000074 {
75 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out);
76
77 // Write the type plane for types first because earlier planes (e.g. for a
78 // primitive type like float) may have constants constructed using types
79 // coming later (e.g., via getelementptr from a pointer type). The type
80 // plane is needed before types can be fwd or bkwd referenced.
81 const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
82 assert(!Plane.empty() && "No types at all?");
83 unsigned ValNo = Type::FirstDerivedTyID; // Start at the derived types...
84 outputConstantsInPlane(Plane, ValNo); // Write out the types
85 }
Chris Lattner00950542001-06-06 20:29:01 +000086
Chris Lattnerd6942d72004-01-14 16:54:21 +000087 DEBUG(for (unsigned i = 0; i != Type::TypeTyID; ++i)
88 if (Table.getPlane(i).size())
89 std::cerr << " ModuleLevel["
90 << *Type::getPrimitiveType((Type::PrimitiveID)i)
91 << "] = " << Table.getPlane(i).size() << "\n");
92
Chris Lattner186a1f72003-03-19 20:56:46 +000093 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +000094 outputModuleInfoBlock(M);
95
Chris Lattner186a1f72003-03-19 20:56:46 +000096 // Output module level constants, used for global variable initializers
97 outputConstants(false);
98
Chris Lattnerb5794002002-04-07 22:49:37 +000099 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000100 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000101 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000102
103 // If needed, output the symbol table for the module...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000104 outputSymbolTable(M->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000105}
106
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000107// Helper function for outputConstants().
108// Writes out all the constants in the plane Plane starting at entry StartNo.
109//
110void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
111 &Plane, unsigned StartNo) {
112 unsigned ValNo = StartNo;
113
Chris Lattner186a1f72003-03-19 20:56:46 +0000114 // Scan through and ignore function arguments/global values...
115 for (; ValNo < Plane.size() && (isa<Argument>(Plane[ValNo]) ||
116 isa<GlobalValue>(Plane[ValNo])); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000117 /*empty*/;
118
119 unsigned NC = ValNo; // Number of constants
120 for (; NC < Plane.size() &&
121 (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++)
122 /*empty*/;
123 NC -= ValNo; // Convert from index into count
124 if (NC == 0) return; // Skip empty type planes...
125
Chris Lattnerd6942d72004-01-14 16:54:21 +0000126 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
127 // more compactly.
128
129 ConstantPlaneHeaderBytes -= Out.size();
130
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000131 // Output type header: [num entries][type id number]
132 //
133 output_vbr(NC, Out);
134
135 // Output the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000136 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000137 assert (Slot != -1 && "Type in constant pool but not in function!!");
138 output_vbr((unsigned)Slot, Out);
139
Chris Lattnerd6942d72004-01-14 16:54:21 +0000140 ConstantPlaneHeaderBytes += Out.size();
141
142
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000143 //cerr << "Emitting " << NC << " constants of type '"
144 // << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n";
145
146 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
147 const Value *V = Plane[i];
148 if (const Constant *CPV = dyn_cast<Constant>(V)) {
149 //cerr << "Serializing value: <" << V->getType() << ">: " << V << ":"
150 // << Out.size() << "\n";
151 outputConstant(CPV);
152 } else {
Chris Lattner186a1f72003-03-19 20:56:46 +0000153 outputType(cast<Type>(V));
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000154 }
155 }
156}
157
Chris Lattner79df7c02002-03-26 18:01:55 +0000158void BytecodeWriter::outputConstants(bool isFunction) {
Chris Lattnerd6942d72004-01-14 16:54:21 +0000159 ConstantTotalBytes -= Out.size();
160 if (isFunction) FunctionConstantTotalBytes -= Out.size();
Chris Lattnere8fdde12001-09-07 16:39:41 +0000161 BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out);
Chris Lattner00950542001-06-06 20:29:01 +0000162
163 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000164
165 // Output the type plane before any constants!
166 if (isFunction && NumPlanes > Type::TypeTyID) {
167 const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000168 if (!Plane.empty()) { // Skip empty type planes...
Chris Lattnerf69315b2003-05-22 18:35:38 +0000169 unsigned ValNo = Table.getModuleLevel(Type::TypeTyID);
170 outputConstantsInPlane(Plane, ValNo);
Chris Lattner6463e0d2002-10-14 03:34:17 +0000171 }
Chris Lattner00950542001-06-06 20:29:01 +0000172 }
Chris Lattnerf69315b2003-05-22 18:35:38 +0000173
174 for (unsigned pno = 0; pno != NumPlanes; pno++)
175 if (pno != Type::TypeTyID) { // Type plane handled above.
176 const std::vector<const Value*> &Plane = Table.getPlane(pno);
177 if (!Plane.empty()) { // Skip empty type planes...
178 unsigned ValNo = 0;
Misha Brukman37f92e22003-09-11 22:34:13 +0000179 if (isFunction) // Don't re-emit module constants
Chris Lattnerf69315b2003-05-22 18:35:38 +0000180 ValNo += Table.getModuleLevel(pno);
181
182 if (pno >= Type::FirstDerivedTyID) {
183 // Skip zero initializer
184 if (ValNo == 0)
185 ValNo = 1;
186 }
187
188 // Write out constants in the plane
189 outputConstantsInPlane(Plane, ValNo);
190 }
191 }
Chris Lattnerd6942d72004-01-14 16:54:21 +0000192 ConstantTotalBytes += Out.size();
193 if (isFunction) FunctionConstantTotalBytes += Out.size();
Chris Lattner00950542001-06-06 20:29:01 +0000194}
195
Chris Lattner6b252422003-10-16 18:28:50 +0000196static unsigned getEncodedLinkage(const GlobalValue *GV) {
197 switch (GV->getLinkage()) {
198 default: assert(0 && "Invalid linkage!");
199 case GlobalValue::ExternalLinkage: return 0;
Chris Lattner6b252422003-10-16 18:28:50 +0000200 case GlobalValue::WeakLinkage: return 1;
201 case GlobalValue::AppendingLinkage: return 2;
202 case GlobalValue::InternalLinkage: return 3;
Chris Lattner22482a12003-10-18 06:30:21 +0000203 case GlobalValue::LinkOnceLinkage: return 4;
Chris Lattner6b252422003-10-16 18:28:50 +0000204 }
205}
206
Chris Lattner00950542001-06-06 20:29:01 +0000207void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Chris Lattnerd6942d72004-01-14 16:54:21 +0000208 ModuleInfoBytes -= Out.size();
209
Chris Lattner00950542001-06-06 20:29:01 +0000210 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);
211
Chris Lattner70cc3392001-09-10 07:58:01 +0000212 // Output the types for the global variables in the module...
213 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000214 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000215 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000216
Chris Lattner22482a12003-10-18 06:30:21 +0000217 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
218 // bit5+ = Slot # for type
219 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000220 (I->hasInitializer() << 1) | I->isConstant();
Chris Lattnerd70684f2001-09-18 04:01:05 +0000221 output_vbr(oSlot, Out);
222
Chris Lattner1b98c5c2001-10-13 06:48:38 +0000223 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000224 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000225 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +0000226 assert(Slot != -1 && "No slot for global var initializer!");
227 output_vbr((unsigned)Slot, Out);
228 }
Chris Lattner70cc3392001-09-10 07:58:01 +0000229 }
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000230 output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
Chris Lattner70cc3392001-09-10 07:58:01 +0000231
Chris Lattnerb5794002002-04-07 22:49:37 +0000232 // Output the types of the functions in this module...
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000233 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000234 int Slot = Table.getSlot(I->getType());
Chris Lattner00950542001-06-06 20:29:01 +0000235 assert(Slot != -1 && "Module const pool is broken!");
236 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
237 output_vbr((unsigned)Slot, Out);
Chris Lattner00950542001-06-06 20:29:01 +0000238 }
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000239 output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);
Chris Lattner70cc3392001-09-10 07:58:01 +0000240
Chris Lattner00950542001-06-06 20:29:01 +0000241 align32(Out);
Chris Lattnerd6942d72004-01-14 16:54:21 +0000242
243 ModuleInfoBytes += Out.size();
Chris Lattner00950542001-06-06 20:29:01 +0000244}
245
Chris Lattner186a1f72003-03-19 20:56:46 +0000246void BytecodeWriter::outputFunction(const Function *F) {
Chris Lattnerc9aa7df2002-03-29 03:51:11 +0000247 BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);
Chris Lattner6b252422003-10-16 18:28:50 +0000248 output_vbr(getEncodedLinkage(F), Out);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000249 // Only output the constant pool and other goodies if needed...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000250 if (!F->isExternal()) {
Chris Lattnerd23b1d32001-11-26 18:56:10 +0000251
Chris Lattnerb5794002002-04-07 22:49:37 +0000252 // Get slot information about the function...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000253 Table.incorporateFunction(F);
Chris Lattner00950542001-06-06 20:29:01 +0000254
Chris Lattnerb5794002002-04-07 22:49:37 +0000255 // Output information about the constants in the function...
Chris Lattnere8fdde12001-09-07 16:39:41 +0000256 outputConstants(true);
Chris Lattner00950542001-06-06 20:29:01 +0000257
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000258 { // Output all of the instructions in the body of the function
259 BytecodeBlock ILBlock(BytecodeFormat::InstructionList, Out);
Chris Lattnerd6942d72004-01-14 16:54:21 +0000260 InstructionBytes -= Out.size();
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000261 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E;++BB)
262 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I)
263 processInstruction(*I);
Chris Lattnerd6942d72004-01-14 16:54:21 +0000264 InstructionBytes += Out.size();
Chris Lattner8d1dbd22003-12-01 07:05:31 +0000265 }
Chris Lattnere8fdde12001-09-07 16:39:41 +0000266
Chris Lattnerb5794002002-04-07 22:49:37 +0000267 // If needed, output the symbol table for the function...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000268 outputSymbolTable(F->getSymbolTable());
Chris Lattnere8fdde12001-09-07 16:39:41 +0000269
Chris Lattnerb5794002002-04-07 22:49:37 +0000270 Table.purgeFunction();
Chris Lattnere8fdde12001-09-07 16:39:41 +0000271 }
Chris Lattner00950542001-06-06 20:29:01 +0000272}
273
Chris Lattner00950542001-06-06 20:29:01 +0000274void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattner737d3cd2004-01-10 19:56:59 +0000275 // Do not output the Bytecode block for an empty symbol table, it just wastes
276 // space!
277 if (MST.begin() == MST.end()) return;
278
Chris Lattnerd6942d72004-01-14 16:54:21 +0000279 SymTabBytes -= Out.size();
280
281 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTable, Out);
Chris Lattner00950542001-06-06 20:29:01 +0000282
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000283 for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {
Chris Lattner00950542001-06-06 20:29:01 +0000284 SymbolTable::type_const_iterator I = MST.type_begin(TI->first);
285 SymbolTable::type_const_iterator End = MST.type_end(TI->first);
286 int Slot;
287
288 if (I == End) continue; // Don't mess with an absent type...
289
290 // Symtab block header: [num entries][type id number]
291 output_vbr(MST.type_size(TI->first), Out);
292
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000293 Slot = Table.getSlot(TI->first);
Chris Lattner00950542001-06-06 20:29:01 +0000294 assert(Slot != -1 && "Type in symtab, but not in table!");
295 output_vbr((unsigned)Slot, Out);
296
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000297 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +0000298 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000299 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000300 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Chris Lattner00950542001-06-06 20:29:01 +0000301 output_vbr((unsigned)Slot, Out);
302 output(I->first, Out, false); // Don't force alignment...
303 }
304 }
Chris Lattnerd6942d72004-01-14 16:54:21 +0000305
306 SymTabBytes += Out.size();
Chris Lattner00950542001-06-06 20:29:01 +0000307}
308
Chris Lattner44f549b2004-01-10 18:49:43 +0000309void llvm::WriteBytecodeToFile(const Module *C, std::ostream &Out) {
Chris Lattnere8fdde12001-09-07 16:39:41 +0000310 assert(C && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +0000311
Chris Lattner697954c2002-01-20 22:54:45 +0000312 std::deque<unsigned char> Buffer;
Chris Lattner00950542001-06-06 20:29:01 +0000313
314 // This object populates buffer for us...
315 BytecodeWriter BCW(Buffer, C);
316
Chris Lattnerce6ef112002-07-26 18:40:14 +0000317 // Keep track of how much we've written...
318 BytesWritten += Buffer.size();
319
Chris Lattnere8fdde12001-09-07 16:39:41 +0000320 // Okay, write the deque out to the ostream now... the deque is not
321 // sequential in memory, however, so write out as much as possible in big
322 // chunks, until we're done.
323 //
Chris Lattner697954c2002-01-20 22:54:45 +0000324 std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
Chris Lattnere8fdde12001-09-07 16:39:41 +0000325 while (I != E) { // Loop until it's all written
326 // Scan to see how big this chunk is...
327 const unsigned char *ChunkPtr = &*I;
328 const unsigned char *LastPtr = ChunkPtr;
329 while (I != E) {
330 const unsigned char *ThisPtr = &*++I;
Chris Lattner5cb17412001-11-04 21:32:41 +0000331 if (LastPtr+1 != ThisPtr) { // Advanced by more than a byte of memory?
332 ++LastPtr;
333 break;
334 }
Chris Lattnere8fdde12001-09-07 16:39:41 +0000335 LastPtr = ThisPtr;
336 }
337
338 // Write out the chunk...
Chris Lattner697954c2002-01-20 22:54:45 +0000339 Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000340 }
341
Chris Lattner00950542001-06-06 20:29:01 +0000342 Out.flush();
343}