fix encoding of invoke instructions. kc++ now round trips
[oota-llvm.git] / lib / Bitcode / Writer / BitcodeWriter.cpp
1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Bitcode writer implementation.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "llvm/Bitcode/BitstreamWriter.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "ValueEnumerator.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/ParameterAttributes.h"
23 #include "llvm/TypeSymbolTable.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/Support/MathExtras.h"
26 using namespace llvm;
27
28 static const unsigned CurVersion = 0;
29
30 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
31   switch (Opcode) {
32   default: assert(0 && "Unknown cast instruction!");
33   case Instruction::Trunc   : return bitc::CAST_TRUNC;
34   case Instruction::ZExt    : return bitc::CAST_ZEXT;
35   case Instruction::SExt    : return bitc::CAST_SEXT;
36   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
37   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
38   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
39   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
40   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
41   case Instruction::FPExt   : return bitc::CAST_FPEXT;
42   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
43   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
44   case Instruction::BitCast : return bitc::CAST_BITCAST;
45   }
46 }
47
48 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
49   switch (Opcode) {
50   default: assert(0 && "Unknown binary instruction!");
51   case Instruction::Add:  return bitc::BINOP_ADD;
52   case Instruction::Sub:  return bitc::BINOP_SUB;
53   case Instruction::Mul:  return bitc::BINOP_MUL;
54   case Instruction::UDiv: return bitc::BINOP_UDIV;
55   case Instruction::FDiv:
56   case Instruction::SDiv: return bitc::BINOP_SDIV;
57   case Instruction::URem: return bitc::BINOP_UREM;
58   case Instruction::FRem:
59   case Instruction::SRem: return bitc::BINOP_SREM;
60   case Instruction::Shl:  return bitc::BINOP_SHL;
61   case Instruction::LShr: return bitc::BINOP_LSHR;
62   case Instruction::AShr: return bitc::BINOP_ASHR;
63   case Instruction::And:  return bitc::BINOP_AND;
64   case Instruction::Or:   return bitc::BINOP_OR;
65   case Instruction::Xor:  return bitc::BINOP_XOR;
66   }
67 }
68
69
70
71 static void WriteStringRecord(unsigned Code, const std::string &Str, 
72                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
73   SmallVector<unsigned, 64> Vals;
74   
75   // Code: [strlen, strchar x N]
76   Vals.push_back(Str.size());
77   for (unsigned i = 0, e = Str.size(); i != e; ++i)
78     Vals.push_back(Str[i]);
79     
80   // Emit the finished record.
81   Stream.EmitRecord(Code, Vals, AbbrevToUse);
82 }
83
84 // Emit information about parameter attributes.
85 static void WriteParamAttrTable(const ValueEnumerator &VE, 
86                                 BitstreamWriter &Stream) {
87   const std::vector<const ParamAttrsList*> &Attrs = VE.getParamAttrs();
88   if (Attrs.empty()) return;
89   
90   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
91
92   SmallVector<uint64_t, 64> Record;
93   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
94     const ParamAttrsList *A = Attrs[i];
95     for (unsigned op = 0, e = A->size(); op != e; ++op) {
96       Record.push_back(A->getParamIndex(op));
97       Record.push_back(A->getParamAttrsAtIndex(op));
98     }
99     
100     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
101     Record.clear();
102   }
103   
104   Stream.ExitBlock();
105 }
106
107 /// WriteTypeTable - Write out the type table for a module.
108 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
109   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
110   
111   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
112   SmallVector<uint64_t, 64> TypeVals;
113   
114   // FIXME: Set up abbrevs now that we know the width of the type fields, etc.
115   
116   // Emit an entry count so the reader can reserve space.
117   TypeVals.push_back(TypeList.size());
118   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
119   TypeVals.clear();
120   
121   // Loop over all of the types, emitting each in turn.
122   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
123     const Type *T = TypeList[i].first;
124     int AbbrevToUse = 0;
125     unsigned Code = 0;
126     
127     switch (T->getTypeID()) {
128     case Type::PackedStructTyID: // FIXME: Delete Type::PackedStructTyID.
129     default: assert(0 && "Unknown type!");
130     case Type::VoidTyID:   Code = bitc::TYPE_CODE_VOID;   break;
131     case Type::FloatTyID:  Code = bitc::TYPE_CODE_FLOAT;  break;
132     case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
133     case Type::LabelTyID:  Code = bitc::TYPE_CODE_LABEL;  break;
134     case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
135     case Type::IntegerTyID:
136       // INTEGER: [width]
137       Code = bitc::TYPE_CODE_INTEGER;
138       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
139       break;
140     case Type::PointerTyID:
141       // POINTER: [pointee type]
142       Code = bitc::TYPE_CODE_POINTER;
143       TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType()));
144       break;
145
146     case Type::FunctionTyID: {
147       const FunctionType *FT = cast<FunctionType>(T);
148       // FUNCTION: [isvararg, attrid, #pararms, paramty x N]
149       Code = bitc::TYPE_CODE_FUNCTION;
150       TypeVals.push_back(FT->isVarArg());
151       TypeVals.push_back(VE.getParamAttrID(FT->getParamAttrs()));
152       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
153       TypeVals.push_back(FT->getNumParams());
154       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
155         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
156       break;
157     }
158     case Type::StructTyID: {
159       const StructType *ST = cast<StructType>(T);
160       // STRUCT: [ispacked, #elts, eltty x N]
161       Code = bitc::TYPE_CODE_STRUCT;
162       TypeVals.push_back(ST->isPacked());
163       TypeVals.push_back(ST->getNumElements());
164       // Output all of the element types...
165       for (StructType::element_iterator I = ST->element_begin(),
166            E = ST->element_end(); I != E; ++I)
167         TypeVals.push_back(VE.getTypeID(*I));
168       break;
169     }
170     case Type::ArrayTyID: {
171       const ArrayType *AT = cast<ArrayType>(T);
172       // ARRAY: [numelts, eltty]
173       Code = bitc::TYPE_CODE_ARRAY;
174       TypeVals.push_back(AT->getNumElements());
175       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
176       break;
177     }
178     case Type::VectorTyID: {
179       const VectorType *VT = cast<VectorType>(T);
180       // VECTOR [numelts, eltty]
181       Code = bitc::TYPE_CODE_VECTOR;
182       TypeVals.push_back(VT->getNumElements());
183       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
184       break;
185     }
186     }
187
188     // Emit the finished record.
189     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
190     TypeVals.clear();
191   }
192   
193   Stream.ExitBlock();
194 }
195
196 static unsigned getEncodedLinkage(const GlobalValue *GV) {
197   switch (GV->getLinkage()) {
198   default: assert(0 && "Invalid linkage!");
199   case GlobalValue::ExternalLinkage:     return 0;
200   case GlobalValue::WeakLinkage:         return 1;
201   case GlobalValue::AppendingLinkage:    return 2;
202   case GlobalValue::InternalLinkage:     return 3;
203   case GlobalValue::LinkOnceLinkage:     return 4;
204   case GlobalValue::DLLImportLinkage:    return 5;
205   case GlobalValue::DLLExportLinkage:    return 6;
206   case GlobalValue::ExternalWeakLinkage: return 7;
207   }
208 }
209
210 static unsigned getEncodedVisibility(const GlobalValue *GV) {
211   switch (GV->getVisibility()) {
212   default: assert(0 && "Invalid visibility!");
213   case GlobalValue::DefaultVisibility:   return 0;
214   case GlobalValue::HiddenVisibility:    return 1;
215   case GlobalValue::ProtectedVisibility: return 2;
216   }
217 }
218
219 // Emit top-level description of module, including target triple, inline asm,
220 // descriptors for global variables, and function prototype info.
221 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
222                             BitstreamWriter &Stream) {
223   // Emit the list of dependent libraries for the Module.
224   for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
225     WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
226
227   // Emit various pieces of data attached to a module.
228   if (!M->getTargetTriple().empty())
229     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
230                       0/*TODO*/, Stream);
231   if (!M->getDataLayout().empty())
232     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
233                       0/*TODO*/, Stream);
234   if (!M->getModuleInlineAsm().empty())
235     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
236                       0/*TODO*/, Stream);
237
238   // Emit information about sections, computing how many there are.  Also
239   // compute the maximum alignment value.
240   std::map<std::string, unsigned> SectionMap;
241   unsigned MaxAlignment = 0;
242   unsigned MaxGlobalType = 0;
243   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
244        GV != E; ++GV) {
245     MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
246     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
247     
248     if (!GV->hasSection()) continue;
249     // Give section names unique ID's.
250     unsigned &Entry = SectionMap[GV->getSection()];
251     if (Entry != 0) continue;
252     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
253                       0/*TODO*/, Stream);
254     Entry = SectionMap.size();
255   }
256   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
257     MaxAlignment = std::max(MaxAlignment, F->getAlignment());
258     if (!F->hasSection()) continue;
259     // Give section names unique ID's.
260     unsigned &Entry = SectionMap[F->getSection()];
261     if (Entry != 0) continue;
262     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
263                       0/*TODO*/, Stream);
264     Entry = SectionMap.size();
265   }
266   
267   // Emit abbrev for globals, now that we know # sections and max alignment.
268   unsigned SimpleGVarAbbrev = 0;
269   if (!M->global_empty()) { 
270     // Add an abbrev for common globals with no visibility or thread localness.
271     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
272     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
273     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
274                               Log2_32_Ceil(MaxGlobalType+1)));
275     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 1)); // Constant.
276     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
277     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 3)); // Linkage.
278     if (MaxAlignment == 0)                                     // Alignment.
279       Abbv->Add(BitCodeAbbrevOp(0));
280     else {
281       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
282       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
283                                Log2_32_Ceil(MaxEncAlignment+1)));
284     }
285     if (SectionMap.empty())                                    // Section.
286       Abbv->Add(BitCodeAbbrevOp(0));
287     else
288       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
289                                Log2_32_Ceil(SectionMap.size()+1)));
290     // Don't bother emitting vis + thread local.
291     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
292   }
293   
294   // Emit the global variable information.
295   SmallVector<unsigned, 64> Vals;
296   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
297        GV != E; ++GV) {
298     unsigned AbbrevToUse = 0;
299
300     // GLOBALVAR: [type, isconst, initid, 
301     //             linkage, alignment, section, visibility, threadlocal]
302     Vals.push_back(VE.getTypeID(GV->getType()));
303     Vals.push_back(GV->isConstant());
304     Vals.push_back(GV->isDeclaration() ? 0 :
305                    (VE.getValueID(GV->getInitializer()) + 1));
306     Vals.push_back(getEncodedLinkage(GV));
307     Vals.push_back(Log2_32(GV->getAlignment())+1);
308     Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
309     if (GV->isThreadLocal() || 
310         GV->getVisibility() != GlobalValue::DefaultVisibility) {
311       Vals.push_back(getEncodedVisibility(GV));
312       Vals.push_back(GV->isThreadLocal());
313     } else {
314       AbbrevToUse = SimpleGVarAbbrev;
315     }
316     
317     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
318     Vals.clear();
319   }
320
321   // Emit the function proto information.
322   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
323     // FUNCTION:  [type, callingconv, isproto, linkage, alignment, section,
324     //             visibility]
325     Vals.push_back(VE.getTypeID(F->getType()));
326     Vals.push_back(F->getCallingConv());
327     Vals.push_back(F->isDeclaration());
328     Vals.push_back(getEncodedLinkage(F));
329     Vals.push_back(Log2_32(F->getAlignment())+1);
330     Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
331     Vals.push_back(getEncodedVisibility(F));
332     
333     unsigned AbbrevToUse = 0;
334     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
335     Vals.clear();
336   }
337   
338   
339   // Emit the alias information.
340   for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
341        AI != E; ++AI) {
342     Vals.push_back(VE.getTypeID(AI->getType()));
343     Vals.push_back(VE.getValueID(AI->getAliasee()));
344     Vals.push_back(getEncodedLinkage(AI));
345     unsigned AbbrevToUse = 0;
346     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
347     Vals.clear();
348   }
349 }
350
351
352 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
353                            const ValueEnumerator &VE,
354                            BitstreamWriter &Stream) {
355   if (FirstVal == LastVal) return;
356   
357   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 2);
358
359   // FIXME: Install and use abbrevs to reduce size.  Install them globally so
360   // they don't need to be reemitted for each function body.
361   
362   SmallVector<uint64_t, 64> Record;
363
364   const ValueEnumerator::ValueList &Vals = VE.getValues();
365   const Type *LastTy = 0;
366   for (unsigned i = FirstVal; i != LastVal; ++i) {
367     const Value *V = Vals[i].first;
368     // If we need to switch types, do so now.
369     if (V->getType() != LastTy) {
370       LastTy = V->getType();
371       Record.push_back(VE.getTypeID(LastTy));
372       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record);
373       Record.clear();
374     }
375     
376     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
377       assert(0 && IA && "FIXME: Inline asm writing unimp!");
378       continue;
379     }
380     const Constant *C = cast<Constant>(V);
381     unsigned Code = -1U;
382     unsigned AbbrevToUse = 0;
383     if (C->isNullValue()) {
384       Code = bitc::CST_CODE_NULL;
385     } else if (isa<UndefValue>(C)) {
386       Code = bitc::CST_CODE_UNDEF;
387     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
388       if (IV->getBitWidth() <= 64) {
389         int64_t V = IV->getSExtValue();
390         if (V >= 0)
391           Record.push_back(V << 1);
392         else
393           Record.push_back((-V << 1) | 1);
394         Code = bitc::CST_CODE_INTEGER;
395       } else {                             // Wide integers, > 64 bits in size.
396         // We have an arbitrary precision integer value to write whose 
397         // bit width is > 64. However, in canonical unsigned integer 
398         // format it is likely that the high bits are going to be zero.
399         // So, we only write the number of active words.
400         unsigned NWords = IV->getValue().getActiveWords(); 
401         const uint64_t *RawWords = IV->getValue().getRawData();
402         Record.push_back(NWords);
403         for (unsigned i = 0; i != NWords; ++i) {
404           int64_t V = RawWords[i];
405           if (V >= 0)
406             Record.push_back(V << 1);
407           else
408             Record.push_back((-V << 1) | 1);
409         }
410         Code = bitc::CST_CODE_WIDE_INTEGER;
411       }
412     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
413       Code = bitc::CST_CODE_FLOAT;
414       if (CFP->getType() == Type::FloatTy) {
415         Record.push_back(FloatToBits((float)CFP->getValue()));
416       } else {
417         assert (CFP->getType() == Type::DoubleTy && "Unknown FP type!");
418         Record.push_back(DoubleToBits((double)CFP->getValue()));
419       }
420     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
421                isa<ConstantVector>(V)) {
422       Code = bitc::CST_CODE_AGGREGATE;
423       Record.push_back(C->getNumOperands());
424       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
425         Record.push_back(VE.getValueID(C->getOperand(i)));
426     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
427       switch (CE->getOpcode()) {
428       default:
429         if (Instruction::isCast(CE->getOpcode())) {
430           Code = bitc::CST_CODE_CE_CAST;
431           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
432           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
433           Record.push_back(VE.getValueID(C->getOperand(0)));
434         } else {
435           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
436           Code = bitc::CST_CODE_CE_BINOP;
437           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
438           Record.push_back(VE.getValueID(C->getOperand(0)));
439           Record.push_back(VE.getValueID(C->getOperand(1)));
440         }
441         break;
442       case Instruction::GetElementPtr:
443         Code = bitc::CST_CODE_CE_GEP;
444         Record.push_back(CE->getNumOperands());
445         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
446           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
447           Record.push_back(VE.getValueID(C->getOperand(i)));
448         }
449         break;
450       case Instruction::Select:
451         Code = bitc::CST_CODE_CE_SELECT;
452         Record.push_back(VE.getValueID(C->getOperand(0)));
453         Record.push_back(VE.getValueID(C->getOperand(1)));
454         Record.push_back(VE.getValueID(C->getOperand(2)));
455         break;
456       case Instruction::ExtractElement:
457         Code = bitc::CST_CODE_CE_EXTRACTELT;
458         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
459         Record.push_back(VE.getValueID(C->getOperand(0)));
460         Record.push_back(VE.getValueID(C->getOperand(1)));
461         break;
462       case Instruction::InsertElement:
463         Code = bitc::CST_CODE_CE_INSERTELT;
464         Record.push_back(VE.getValueID(C->getOperand(0)));
465         Record.push_back(VE.getValueID(C->getOperand(1)));
466         Record.push_back(VE.getValueID(C->getOperand(2)));
467         break;
468       case Instruction::ShuffleVector:
469         Code = bitc::CST_CODE_CE_SHUFFLEVEC;
470         Record.push_back(VE.getValueID(C->getOperand(0)));
471         Record.push_back(VE.getValueID(C->getOperand(1)));
472         Record.push_back(VE.getValueID(C->getOperand(2)));
473         break;
474       case Instruction::ICmp:
475       case Instruction::FCmp:
476         Code = bitc::CST_CODE_CE_CMP;
477         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
478         Record.push_back(VE.getValueID(C->getOperand(0)));
479         Record.push_back(VE.getValueID(C->getOperand(1)));
480         Record.push_back(CE->getPredicate());
481         break;
482       }
483     } else {
484       assert(0 && "Unknown constant!");
485     }
486     Stream.EmitRecord(Code, Record, AbbrevToUse);
487     Record.clear();
488   }
489
490   Stream.ExitBlock();
491 }
492
493 static void WriteModuleConstants(const ValueEnumerator &VE,
494                                  BitstreamWriter &Stream) {
495   const ValueEnumerator::ValueList &Vals = VE.getValues();
496   
497   // Find the first constant to emit, which is the first non-globalvalue value.
498   // We know globalvalues have been emitted by WriteModuleInfo.
499   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
500     if (!isa<GlobalValue>(Vals[i].first)) {
501       WriteConstants(i, Vals.size(), VE, Stream);
502       return;
503     }
504   }
505 }
506
507 /// WriteInstruction - Emit an instruction to the specified stream.
508 static void WriteInstruction(const Instruction &I, ValueEnumerator &VE, 
509                              BitstreamWriter &Stream,
510                              SmallVector<unsigned, 64> &Vals) {
511   unsigned Code = 0;
512   unsigned AbbrevToUse = 0;
513   switch (I.getOpcode()) {
514   default:
515     if (Instruction::isCast(I.getOpcode())) {
516       Code = bitc::FUNC_CODE_INST_CAST;
517       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
518       Vals.push_back(VE.getTypeID(I.getType()));
519       Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
520       Vals.push_back(VE.getValueID(I.getOperand(0)));
521     } else {
522       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
523       Code = bitc::FUNC_CODE_INST_BINOP;
524       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
525       Vals.push_back(VE.getTypeID(I.getType()));
526       Vals.push_back(VE.getValueID(I.getOperand(0)));
527       Vals.push_back(VE.getValueID(I.getOperand(1)));
528     }
529     break;
530
531   case Instruction::GetElementPtr:
532     Code = bitc::FUNC_CODE_INST_GEP;
533     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
534       Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
535       Vals.push_back(VE.getValueID(I.getOperand(i)));
536     }
537     break;
538   case Instruction::Select:
539     Code = bitc::FUNC_CODE_INST_SELECT;
540     Vals.push_back(VE.getTypeID(I.getType()));
541     Vals.push_back(VE.getValueID(I.getOperand(0)));
542     Vals.push_back(VE.getValueID(I.getOperand(1)));
543     Vals.push_back(VE.getValueID(I.getOperand(2)));
544     break;
545   case Instruction::ExtractElement:
546     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
547     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
548     Vals.push_back(VE.getValueID(I.getOperand(0)));
549     Vals.push_back(VE.getValueID(I.getOperand(1)));
550     break;
551   case Instruction::InsertElement:
552     Code = bitc::FUNC_CODE_INST_INSERTELT;
553     Vals.push_back(VE.getTypeID(I.getType()));
554     Vals.push_back(VE.getValueID(I.getOperand(0)));
555     Vals.push_back(VE.getValueID(I.getOperand(1)));
556     Vals.push_back(VE.getValueID(I.getOperand(2)));
557     break;
558   case Instruction::ShuffleVector:
559     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
560     Vals.push_back(VE.getTypeID(I.getType()));
561     Vals.push_back(VE.getValueID(I.getOperand(0)));
562     Vals.push_back(VE.getValueID(I.getOperand(1)));
563     Vals.push_back(VE.getValueID(I.getOperand(2)));
564     break;
565   case Instruction::ICmp:
566   case Instruction::FCmp:
567     Code = bitc::FUNC_CODE_INST_CMP;
568     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
569     Vals.push_back(VE.getValueID(I.getOperand(0)));
570     Vals.push_back(VE.getValueID(I.getOperand(1)));
571     Vals.push_back(cast<CmpInst>(I).getPredicate());
572     break;
573
574   case Instruction::Ret:
575     Code = bitc::FUNC_CODE_INST_RET;
576     if (I.getNumOperands()) {
577       Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
578       Vals.push_back(VE.getValueID(I.getOperand(0)));
579     }
580     break;
581   case Instruction::Br:
582     Code = bitc::FUNC_CODE_INST_BR;
583     Vals.push_back(VE.getValueID(I.getOperand(0)));
584     if (cast<BranchInst>(I).isConditional()) {
585       Vals.push_back(VE.getValueID(I.getOperand(1)));
586       Vals.push_back(VE.getValueID(I.getOperand(2)));
587     }
588     break;
589   case Instruction::Switch:
590     Code = bitc::FUNC_CODE_INST_SWITCH;
591     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
592     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
593       Vals.push_back(VE.getValueID(I.getOperand(i)));
594     break;
595   case Instruction::Invoke: {
596     Code = bitc::FUNC_CODE_INST_INVOKE;
597     Vals.push_back(cast<InvokeInst>(I).getCallingConv());
598     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
599     Vals.push_back(VE.getValueID(I.getOperand(0)));  // callee
600     Vals.push_back(VE.getValueID(I.getOperand(1)));  // normal
601     Vals.push_back(VE.getValueID(I.getOperand(2)));  // unwind
602     
603     // Emit value #'s for the fixed parameters.
604     const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
605     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
606     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
607       Vals.push_back(VE.getValueID(I.getOperand(i+3)));  // fixed param.
608
609     // Emit type/value pairs for varargs params.
610     if (FTy->isVarArg()) {
611       unsigned NumVarargs = I.getNumOperands()-3-FTy->getNumParams();
612       for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
613            i != e; ++i) {
614         Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
615         Vals.push_back(VE.getValueID(I.getOperand(i)));
616       }
617     }
618     break;
619   }
620   case Instruction::Unwind:
621     Code = bitc::FUNC_CODE_INST_UNWIND;
622     break;
623   case Instruction::Unreachable:
624     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
625     break;
626   
627   case Instruction::PHI:
628     Code = bitc::FUNC_CODE_INST_PHI;
629     Vals.push_back(VE.getTypeID(I.getType()));
630     Vals.push_back(I.getNumOperands());
631     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
632       Vals.push_back(VE.getValueID(I.getOperand(i)));
633     break;
634     
635   case Instruction::Malloc:
636     Code = bitc::FUNC_CODE_INST_MALLOC;
637     Vals.push_back(VE.getTypeID(I.getType()));
638     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
639     Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
640     break;
641     
642   case Instruction::Free:
643     Code = bitc::FUNC_CODE_INST_FREE;
644     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
645     Vals.push_back(VE.getValueID(I.getOperand(0)));
646     break;
647     
648   case Instruction::Alloca:
649     Code = bitc::FUNC_CODE_INST_ALLOCA;
650     Vals.push_back(VE.getTypeID(I.getType()));
651     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
652     Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
653     break;
654     
655   case Instruction::Load:
656     Code = bitc::FUNC_CODE_INST_LOAD;
657     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
658     Vals.push_back(VE.getValueID(I.getOperand(0))); // ptr.
659     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
660     Vals.push_back(cast<LoadInst>(I).isVolatile());
661     break;
662   case Instruction::Store:
663     Code = bitc::FUNC_CODE_INST_STORE;
664     Vals.push_back(VE.getTypeID(I.getOperand(1)->getType()));   // Pointer
665     Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
666     Vals.push_back(VE.getValueID(I.getOperand(1))); // ptr.
667     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
668     Vals.push_back(cast<StoreInst>(I).isVolatile());
669     break;
670   case Instruction::Call: {
671     Code = bitc::FUNC_CODE_INST_CALL;
672     Vals.push_back((cast<CallInst>(I).getCallingConv() << 1) |
673                    cast<CallInst>(I).isTailCall());
674     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
675     Vals.push_back(VE.getValueID(I.getOperand(0)));  // callee
676     
677     // Emit value #'s for the fixed parameters.
678     const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
679     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
680     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
681       Vals.push_back(VE.getValueID(I.getOperand(i+1)));  // fixed param.
682       
683     // Emit type/value pairs for varargs params.
684     if (FTy->isVarArg()) {
685       unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
686       for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
687            i != e; ++i) {
688         Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
689         Vals.push_back(VE.getValueID(I.getOperand(i)));
690       }
691     }
692     break;
693   }
694   case Instruction::VAArg:
695     Code = bitc::FUNC_CODE_INST_VAARG;
696     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
697     Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
698     Vals.push_back(VE.getTypeID(I.getType())); // restype.
699     break;
700   }
701   
702   Stream.EmitRecord(Code, Vals, AbbrevToUse);
703   Vals.clear();
704 }
705
706 // Emit names for globals/functions etc.
707 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
708                                   const ValueEnumerator &VE,
709                                   BitstreamWriter &Stream) {
710   if (VST.empty()) return;
711   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 3);
712   
713   // FIXME: Set up the abbrev, we know how many values there are!
714   // FIXME: We know if the type names can use 7-bit ascii.
715   SmallVector<unsigned, 64> NameVals;
716   
717   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
718        SI != SE; ++SI) {
719     unsigned AbbrevToUse = 0;
720     
721     // VST_ENTRY:   [valueid, namelen, namechar x N]
722     // VST_BBENTRY: [bbid, namelen, namechar x N]
723     unsigned Code;
724     if (isa<BasicBlock>(SI->getValue())) {
725       Code = bitc::VST_CODE_BBENTRY;
726     } else {
727       Code = bitc::VST_CODE_ENTRY;
728     }
729     
730     NameVals.push_back(VE.getValueID(SI->getValue()));
731     NameVals.push_back(SI->getKeyLength());
732     for (const char *P = SI->getKeyData(),
733          *E = SI->getKeyData()+SI->getKeyLength(); P != E; ++P)
734       NameVals.push_back((unsigned char)*P);
735     
736     // Emit the finished record.
737     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
738     NameVals.clear();
739   }
740   Stream.ExitBlock();
741 }
742
743 /// WriteFunction - Emit a function body to the module stream.
744 static void WriteFunction(const Function &F, ValueEnumerator &VE, 
745                           BitstreamWriter &Stream) {
746   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 3);
747   VE.incorporateFunction(F);
748
749   SmallVector<unsigned, 64> Vals;
750   
751   // Emit the number of basic blocks, so the reader can create them ahead of
752   // time.
753   Vals.push_back(VE.getBasicBlocks().size());
754   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
755   Vals.clear();
756   
757   // FIXME: Function attributes?
758   
759   // If there are function-local constants, emit them now.
760   unsigned CstStart, CstEnd;
761   VE.getFunctionConstantRange(CstStart, CstEnd);
762   WriteConstants(CstStart, CstEnd, VE, Stream);
763   
764   // Finally, emit all the instructions, in order.
765   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
766     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
767       WriteInstruction(*I, VE, Stream, Vals);
768   
769   // Emit names for all the instructions etc.
770   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
771     
772   VE.purgeFunction();
773   Stream.ExitBlock();
774 }
775
776 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
777 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
778                                  const ValueEnumerator &VE,
779                                  BitstreamWriter &Stream) {
780   if (TST.empty()) return;
781   
782   Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
783   
784   // FIXME: Set up the abbrev, we know how many types there are!
785   // FIXME: We know if the type names can use 7-bit ascii.
786   
787   SmallVector<unsigned, 64> NameVals;
788   
789   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
790        TI != TE; ++TI) {
791     unsigned AbbrevToUse = 0;
792     
793     // TST_ENTRY: [typeid, namelen, namechar x N]
794     NameVals.push_back(VE.getTypeID(TI->second));
795     
796     const std::string &Str = TI->first;
797     NameVals.push_back(Str.size());
798     for (unsigned i = 0, e = Str.size(); i != e; ++i)
799       NameVals.push_back(Str[i]);
800     
801     // Emit the finished record.
802     Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse);
803     NameVals.clear();
804   }
805   
806   Stream.ExitBlock();
807 }
808
809
810 /// WriteModule - Emit the specified module to the bitstream.
811 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
812   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
813   
814   // Emit the version number if it is non-zero.
815   if (CurVersion) {
816     SmallVector<unsigned, 1> Vals;
817     Vals.push_back(CurVersion);
818     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
819   }
820   
821   // Analyze the module, enumerating globals, functions, etc.
822   ValueEnumerator VE(M);
823   
824   // Emit information about parameter attributes.
825   WriteParamAttrTable(VE, Stream);
826   
827   // Emit information describing all of the types in the module.
828   WriteTypeTable(VE, Stream);
829   
830   // Emit top-level description of module, including target triple, inline asm,
831   // descriptors for global variables, and function prototype info.
832   WriteModuleInfo(M, VE, Stream);
833   
834   // Emit constants.
835   WriteModuleConstants(VE, Stream);
836   
837   // If we have any aggregate values in the value table, purge them - these can
838   // only be used to initialize global variables.  Doing so makes the value
839   // namespace smaller for code in functions.
840   int NumNonAggregates = VE.PurgeAggregateValues();
841   if (NumNonAggregates != -1) {
842     SmallVector<unsigned, 1> Vals;
843     Vals.push_back(NumNonAggregates);
844     Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
845   }
846   
847   // Emit function bodies.
848   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
849     if (!I->isDeclaration())
850       WriteFunction(*I, VE, Stream);
851   
852   // Emit the type symbol table information.
853   WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
854   
855   // Emit names for globals/functions etc.
856   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
857   
858   Stream.ExitBlock();
859 }
860
861 /// WriteBitcodeToFile - Write the specified module to the specified output
862 /// stream.
863 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
864   std::vector<unsigned char> Buffer;
865   BitstreamWriter Stream(Buffer);
866   
867   Buffer.reserve(256*1024);
868   
869   // Emit the file header.
870   Stream.Emit((unsigned)'B', 8);
871   Stream.Emit((unsigned)'C', 8);
872   Stream.Emit(0x0, 4);
873   Stream.Emit(0xC, 4);
874   Stream.Emit(0xE, 4);
875   Stream.Emit(0xD, 4);
876
877   // Emit the module.
878   WriteModule(M, Stream);
879   
880   // Write the generated bitstream to "Out".
881   Out.write((char*)&Buffer.front(), Buffer.size());
882 }