add bitcode alias support
[oota-llvm.git] / lib / Bitcode / Writer / BitcodeWriter.cpp
1 //===--- Bitcode/Writer/Writer.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/Module.h"
21 #include "llvm/TypeSymbolTable.h"
22 #include "llvm/ValueSymbolTable.h"
23 #include "llvm/Support/MathExtras.h"
24 using namespace llvm;
25
26 static const unsigned CurVersion = 0;
27
28 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
29   switch (Opcode) {
30   default: assert(0 && "Unknown cast instruction!");
31   case Instruction::Trunc   : return bitc::CAST_TRUNC;
32   case Instruction::ZExt    : return bitc::CAST_ZEXT;
33   case Instruction::SExt    : return bitc::CAST_SEXT;
34   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
35   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
36   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
37   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
38   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
39   case Instruction::FPExt   : return bitc::CAST_FPEXT;
40   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
41   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
42   case Instruction::BitCast : return bitc::CAST_BITCAST;
43   }
44 }
45
46 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
47   switch (Opcode) {
48   default: assert(0 && "Unknown binary instruction!");
49   case Instruction::Add:  return bitc::BINOP_ADD;
50   case Instruction::Sub:  return bitc::BINOP_SUB;
51   case Instruction::Mul:  return bitc::BINOP_MUL;
52   case Instruction::UDiv: return bitc::BINOP_UDIV;
53   case Instruction::FDiv:
54   case Instruction::SDiv: return bitc::BINOP_SDIV;
55   case Instruction::URem: return bitc::BINOP_UREM;
56   case Instruction::FRem:
57   case Instruction::SRem: return bitc::BINOP_SREM;
58   case Instruction::Shl:  return bitc::BINOP_SHL;
59   case Instruction::LShr: return bitc::BINOP_LSHR;
60   case Instruction::AShr: return bitc::BINOP_ASHR;
61   case Instruction::And:  return bitc::BINOP_AND;
62   case Instruction::Or:   return bitc::BINOP_OR;
63   case Instruction::Xor:  return bitc::BINOP_XOR;
64   }
65 }
66
67
68
69 static void WriteStringRecord(unsigned Code, const std::string &Str, 
70                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
71   SmallVector<unsigned, 64> Vals;
72   
73   // Code: [strlen, strchar x N]
74   Vals.push_back(Str.size());
75   for (unsigned i = 0, e = Str.size(); i != e; ++i)
76     Vals.push_back(Str[i]);
77     
78   // Emit the finished record.
79   Stream.EmitRecord(Code, Vals, AbbrevToUse);
80 }
81
82
83 /// WriteTypeTable - Write out the type table for a module.
84 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
85   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
86   
87   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
88   SmallVector<uint64_t, 64> TypeVals;
89   
90   // FIXME: Set up abbrevs now that we know the width of the type fields, etc.
91   
92   // Emit an entry count so the reader can reserve space.
93   TypeVals.push_back(TypeList.size());
94   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
95   TypeVals.clear();
96   
97   // Loop over all of the types, emitting each in turn.
98   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
99     const Type *T = TypeList[i].first;
100     int AbbrevToUse = 0;
101     unsigned Code = 0;
102     
103     switch (T->getTypeID()) {
104     case Type::PackedStructTyID: // FIXME: Delete Type::PackedStructTyID.
105     default: assert(0 && "Unknown type!");
106     case Type::VoidTyID:   Code = bitc::TYPE_CODE_VOID;   break;
107     case Type::FloatTyID:  Code = bitc::TYPE_CODE_FLOAT;  break;
108     case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
109     case Type::LabelTyID:  Code = bitc::TYPE_CODE_LABEL;  break;
110     case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
111     case Type::IntegerTyID:
112       // INTEGER: [width]
113       Code = bitc::TYPE_CODE_INTEGER;
114       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
115       break;
116     case Type::PointerTyID:
117       // POINTER: [pointee type]
118       Code = bitc::TYPE_CODE_POINTER;
119       TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType()));
120       break;
121
122     case Type::FunctionTyID: {
123       const FunctionType *FT = cast<FunctionType>(T);
124       // FUNCTION: [isvararg, #pararms, paramty x N]
125       Code = bitc::TYPE_CODE_FUNCTION;
126       TypeVals.push_back(FT->isVarArg());
127       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
128       // FIXME: PARAM ATTR ID!
129       TypeVals.push_back(FT->getNumParams());
130       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
131         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
132       break;
133     }
134     case Type::StructTyID: {
135       const StructType *ST = cast<StructType>(T);
136       // STRUCT: [ispacked, #elts, eltty x N]
137       Code = bitc::TYPE_CODE_STRUCT;
138       TypeVals.push_back(ST->isPacked());
139       TypeVals.push_back(ST->getNumElements());
140       // Output all of the element types...
141       for (StructType::element_iterator I = ST->element_begin(),
142            E = ST->element_end(); I != E; ++I)
143         TypeVals.push_back(VE.getTypeID(*I));
144       break;
145     }
146     case Type::ArrayTyID: {
147       const ArrayType *AT = cast<ArrayType>(T);
148       // ARRAY: [numelts, eltty]
149       Code = bitc::TYPE_CODE_ARRAY;
150       TypeVals.push_back(AT->getNumElements());
151       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
152       break;
153     }
154     case Type::VectorTyID: {
155       const VectorType *VT = cast<VectorType>(T);
156       // VECTOR [numelts, eltty]
157       Code = bitc::TYPE_CODE_VECTOR;
158       TypeVals.push_back(VT->getNumElements());
159       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
160       break;
161     }
162     }
163
164     // Emit the finished record.
165     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
166     TypeVals.clear();
167   }
168   
169   Stream.ExitBlock();
170 }
171
172 static unsigned getEncodedLinkage(const GlobalValue *GV) {
173   switch (GV->getLinkage()) {
174   default: assert(0 && "Invalid linkage!");
175   case GlobalValue::ExternalLinkage:     return 0;
176   case GlobalValue::WeakLinkage:         return 1;
177   case GlobalValue::AppendingLinkage:    return 2;
178   case GlobalValue::InternalLinkage:     return 3;
179   case GlobalValue::LinkOnceLinkage:     return 4;
180   case GlobalValue::DLLImportLinkage:    return 5;
181   case GlobalValue::DLLExportLinkage:    return 6;
182   case GlobalValue::ExternalWeakLinkage: return 7;
183   }
184 }
185
186 static unsigned getEncodedVisibility(const GlobalValue *GV) {
187   switch (GV->getVisibility()) {
188   default: assert(0 && "Invalid visibility!");
189   case GlobalValue::DefaultVisibility: return 0;
190   case GlobalValue::HiddenVisibility:  return 1;
191   }
192 }
193
194 // Emit top-level description of module, including target triple, inline asm,
195 // descriptors for global variables, and function prototype info.
196 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
197                             BitstreamWriter &Stream) {
198   // Emit the list of dependent libraries for the Module.
199   for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
200     WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
201
202   // Emit various pieces of data attached to a module.
203   if (!M->getTargetTriple().empty())
204     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
205                       0/*TODO*/, Stream);
206   if (!M->getDataLayout().empty())
207     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
208                       0/*TODO*/, Stream);
209   if (!M->getModuleInlineAsm().empty())
210     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
211                       0/*TODO*/, Stream);
212
213   // Emit information about sections, computing how many there are.  Also
214   // compute the maximum alignment value.
215   std::map<std::string, unsigned> SectionMap;
216   unsigned MaxAlignment = 0;
217   unsigned MaxGlobalType = 0;
218   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
219        GV != E; ++GV) {
220     MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
221     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
222     
223     if (!GV->hasSection()) continue;
224     // Give section names unique ID's.
225     unsigned &Entry = SectionMap[GV->getSection()];
226     if (Entry != 0) continue;
227     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
228                       0/*TODO*/, Stream);
229     Entry = SectionMap.size();
230   }
231   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
232     MaxAlignment = std::max(MaxAlignment, F->getAlignment());
233     if (!F->hasSection()) continue;
234     // Give section names unique ID's.
235     unsigned &Entry = SectionMap[F->getSection()];
236     if (Entry != 0) continue;
237     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
238                       0/*TODO*/, Stream);
239     Entry = SectionMap.size();
240   }
241   
242   // Emit abbrev for globals, now that we know # sections and max alignment.
243   unsigned SimpleGVarAbbrev = 0;
244   if (!M->global_empty()) { 
245     // Add an abbrev for common globals with no visibility or thread localness.
246     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
247     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
248     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
249                               Log2_32_Ceil(MaxGlobalType+1)));
250     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 1)); // Constant.
251     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
252     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 3)); // Linkage.
253     if (MaxAlignment == 0)                                     // Alignment.
254       Abbv->Add(BitCodeAbbrevOp(0));
255     else {
256       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
257       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
258                                Log2_32_Ceil(MaxEncAlignment+1)));
259     }
260     if (SectionMap.empty())                                    // Section.
261       Abbv->Add(BitCodeAbbrevOp(0));
262     else
263       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
264                                Log2_32_Ceil(SectionMap.size()+1)));
265     // Don't bother emitting vis + thread local.
266     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
267   }
268   
269   // Emit the global variable information.
270   SmallVector<unsigned, 64> Vals;
271   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
272        GV != E; ++GV) {
273     unsigned AbbrevToUse = 0;
274
275     // GLOBALVAR: [type, isconst, initid, 
276     //             linkage, alignment, section, visibility, threadlocal]
277     Vals.push_back(VE.getTypeID(GV->getType()));
278     Vals.push_back(GV->isConstant());
279     Vals.push_back(GV->isDeclaration() ? 0 :
280                    (VE.getValueID(GV->getInitializer()) + 1));
281     Vals.push_back(getEncodedLinkage(GV));
282     Vals.push_back(Log2_32(GV->getAlignment())+1);
283     Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
284     if (GV->isThreadLocal() || 
285         GV->getVisibility() != GlobalValue::DefaultVisibility) {
286       Vals.push_back(getEncodedVisibility(GV));
287       Vals.push_back(GV->isThreadLocal());
288     } else {
289       AbbrevToUse = SimpleGVarAbbrev;
290     }
291     
292     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
293     Vals.clear();
294   }
295
296   // Emit the function proto information.
297   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
298     // FUNCTION:  [type, callingconv, isproto, linkage, alignment, section,
299     //             visibility]
300     Vals.push_back(VE.getTypeID(F->getType()));
301     Vals.push_back(F->getCallingConv());
302     Vals.push_back(F->isDeclaration());
303     Vals.push_back(getEncodedLinkage(F));
304     Vals.push_back(Log2_32(F->getAlignment())+1);
305     Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
306     Vals.push_back(getEncodedVisibility(F));
307     
308     unsigned AbbrevToUse = 0;
309     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
310     Vals.clear();
311   }
312   
313   
314   // Emit the alias information.
315   for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
316        AI != E; ++AI) {
317     Vals.push_back(VE.getTypeID(AI->getType()));
318     Vals.push_back(VE.getValueID(AI->getAliasee()));
319     Vals.push_back(getEncodedLinkage(AI));
320     unsigned AbbrevToUse = 0;
321     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
322     Vals.clear();
323   }
324 }
325
326
327 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
328 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
329                                  const ValueEnumerator &VE,
330                                  BitstreamWriter &Stream) {
331   if (TST.empty()) return;
332   
333   Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
334   
335   // FIXME: Set up the abbrev, we know how many types there are!
336   // FIXME: We know if the type names can use 7-bit ascii.
337   
338   SmallVector<unsigned, 64> NameVals;
339   
340   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
341        TI != TE; ++TI) {
342     unsigned AbbrevToUse = 0;
343     
344     // TST_ENTRY: [typeid, namelen, namechar x N]
345     NameVals.push_back(VE.getTypeID(TI->second));
346     
347     const std::string &Str = TI->first;
348     NameVals.push_back(Str.size());
349     for (unsigned i = 0, e = Str.size(); i != e; ++i)
350       NameVals.push_back(Str[i]);
351     
352     // Emit the finished record.
353     Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse);
354     NameVals.clear();
355   }
356   
357   Stream.ExitBlock();
358 }
359
360 // Emit names for globals/functions etc.
361 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
362                                   const ValueEnumerator &VE,
363                                   BitstreamWriter &Stream) {
364   if (VST.empty()) return;
365   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 3);
366
367   // FIXME: Set up the abbrev, we know how many values there are!
368   // FIXME: We know if the type names can use 7-bit ascii.
369   SmallVector<unsigned, 64> NameVals;
370
371   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
372        SI != SE; ++SI) {
373     unsigned AbbrevToUse = 0;
374
375     // VST_ENTRY: [valueid, namelen, namechar x N]
376     NameVals.push_back(VE.getValueID(SI->getValue()));
377   
378     NameVals.push_back(SI->getKeyLength());
379     for (const char *P = SI->getKeyData(),
380          *E = SI->getKeyData()+SI->getKeyLength(); P != E; ++P)
381       NameVals.push_back((unsigned char)*P);
382     
383     // Emit the finished record.
384     Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse);
385     NameVals.clear();
386   }
387   Stream.ExitBlock();
388 }
389
390 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
391                            const ValueEnumerator &VE,
392                            BitstreamWriter &Stream) {
393   if (FirstVal == LastVal) return;
394   
395   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 2);
396
397   // FIXME: Install and use abbrevs to reduce size.
398   
399   SmallVector<uint64_t, 64> Record;
400
401   const ValueEnumerator::ValueList &Vals = VE.getValues();
402   const Type *LastTy = 0;
403   for (unsigned i = FirstVal; i != LastVal; ++i) {
404     const Value *V = Vals[i].first;
405     // If we need to switch types, do so now.
406     if (V->getType() != LastTy) {
407       LastTy = V->getType();
408       Record.push_back(VE.getTypeID(LastTy));
409       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record);
410       Record.clear();
411     }
412     
413     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
414       assert(0 && IA && "FIXME: Inline asm writing unimp!");
415       continue;
416     }
417     const Constant *C = cast<Constant>(V);
418     unsigned Code = -1U;
419     unsigned AbbrevToUse = 0;
420     if (C->isNullValue()) {
421       Code = bitc::CST_CODE_NULL;
422     } else if (isa<UndefValue>(C)) {
423       Code = bitc::CST_CODE_UNDEF;
424     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
425       if (IV->getBitWidth() <= 64) {
426         int64_t V = IV->getSExtValue();
427         if (V >= 0)
428           Record.push_back(V << 1);
429         else
430           Record.push_back((-V << 1) | 1);
431         Code = bitc::CST_CODE_INTEGER;
432       } else {                             // Wide integers, > 64 bits in size.
433         // We have an arbitrary precision integer value to write whose 
434         // bit width is > 64. However, in canonical unsigned integer 
435         // format it is likely that the high bits are going to be zero.
436         // So, we only write the number of active words.
437         unsigned NWords = IV->getValue().getActiveWords(); 
438         const uint64_t *RawWords = IV->getValue().getRawData();
439         Record.push_back(NWords);
440         for (unsigned i = 0; i != NWords; ++i) {
441           int64_t V = RawWords[i];
442           if (V >= 0)
443             Record.push_back(V << 1);
444           else
445             Record.push_back((-V << 1) | 1);
446         }
447         Code = bitc::CST_CODE_WIDE_INTEGER;
448       }
449     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
450       Code = bitc::CST_CODE_FLOAT;
451       if (CFP->getType() == Type::FloatTy) {
452         Record.push_back(FloatToBits((float)CFP->getValue()));
453       } else {
454         assert (CFP->getType() == Type::DoubleTy && "Unknown FP type!");
455         Record.push_back(DoubleToBits((double)CFP->getValue()));
456       }
457     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
458                isa<ConstantVector>(V)) {
459       Code = bitc::CST_CODE_AGGREGATE;
460       Record.push_back(C->getNumOperands());
461       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
462         Record.push_back(VE.getValueID(C->getOperand(i)));
463     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
464       switch (CE->getOpcode()) {
465       default:
466         if (Instruction::isCast(CE->getOpcode())) {
467           Code = bitc::CST_CODE_CE_CAST;
468           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
469           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
470           Record.push_back(VE.getValueID(C->getOperand(0)));
471         } else {
472           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
473           Code = bitc::CST_CODE_CE_BINOP;
474           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
475           Record.push_back(VE.getValueID(C->getOperand(0)));
476           Record.push_back(VE.getValueID(C->getOperand(1)));
477         }
478         break;
479       case Instruction::GetElementPtr:
480         Code = bitc::CST_CODE_CE_GEP;
481         Record.push_back(CE->getNumOperands());
482         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
483           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
484           Record.push_back(VE.getValueID(C->getOperand(i)));
485         }
486         break;
487       case Instruction::Select:
488         Code = bitc::CST_CODE_CE_SELECT;
489         Record.push_back(VE.getValueID(C->getOperand(0)));
490         Record.push_back(VE.getValueID(C->getOperand(1)));
491         Record.push_back(VE.getValueID(C->getOperand(2)));
492         break;
493       case Instruction::ExtractElement:
494         Code = bitc::CST_CODE_CE_EXTRACTELT;
495         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
496         Record.push_back(VE.getValueID(C->getOperand(0)));
497         Record.push_back(VE.getValueID(C->getOperand(1)));
498         break;
499       case Instruction::InsertElement:
500         Code = bitc::CST_CODE_CE_INSERTELT;
501         Record.push_back(VE.getValueID(C->getOperand(0)));
502         Record.push_back(VE.getValueID(C->getOperand(1)));
503         Record.push_back(VE.getValueID(C->getOperand(2)));
504         break;
505       case Instruction::ShuffleVector:
506         Code = bitc::CST_CODE_CE_SHUFFLEVEC;
507         Record.push_back(VE.getValueID(C->getOperand(0)));
508         Record.push_back(VE.getValueID(C->getOperand(1)));
509         Record.push_back(VE.getValueID(C->getOperand(2)));
510         break;
511       case Instruction::ICmp:
512       case Instruction::FCmp:
513         Code = bitc::CST_CODE_CE_CMP;
514         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
515         Record.push_back(VE.getValueID(C->getOperand(0)));
516         Record.push_back(VE.getValueID(C->getOperand(1)));
517         Record.push_back(CE->getPredicate());
518         break;
519       }
520     } else {
521       assert(0 && "Unknown constant!");
522     }
523     Stream.EmitRecord(Code, Record, AbbrevToUse);
524     Record.clear();
525   }
526
527   Stream.ExitBlock();
528 }
529
530 static void WriteModuleConstants(const ValueEnumerator &VE,
531                                  BitstreamWriter &Stream) {
532   const ValueEnumerator::ValueList &Vals = VE.getValues();
533   
534   // Find the first constant to emit, which is the first non-globalvalue value.
535   // We know globalvalues have been emitted by WriteModuleInfo.
536   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
537     if (!isa<GlobalValue>(Vals[i].first)) {
538       WriteConstants(i, Vals.size(), VE, Stream);
539       return;
540     }
541   }
542 }
543
544 /// WriteModule - Emit the specified module to the bitstream.
545 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
546   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
547   
548   // Emit the version number if it is non-zero.
549   if (CurVersion) {
550     SmallVector<unsigned, 1> VersionVals;
551     VersionVals.push_back(CurVersion);
552     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, VersionVals);
553   }
554   
555   // Analyze the module, enumerating globals, functions, etc.
556   ValueEnumerator VE(M);
557   
558   // Emit information describing all of the types in the module.
559   WriteTypeTable(VE, Stream);
560   
561   // Emit top-level description of module, including target triple, inline asm,
562   // descriptors for global variables, and function prototype info.
563   WriteModuleInfo(M, VE, Stream);
564   
565   // Emit constants.
566   WriteModuleConstants(VE, Stream);
567   
568   // Emit the type symbol table information.
569   WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
570   
571   // Emit names for globals/functions etc.
572   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
573   
574   Stream.ExitBlock();
575 }
576
577 /// WriteBitcodeToFile - Write the specified module to the specified output
578 /// stream.
579 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
580   std::vector<unsigned char> Buffer;
581   BitstreamWriter Stream(Buffer);
582   
583   Buffer.reserve(256*1024);
584   
585   // Emit the file header.
586   Stream.Emit((unsigned)'B', 8);
587   Stream.Emit((unsigned)'C', 8);
588   Stream.Emit(0x0, 4);
589   Stream.Emit(0xC, 4);
590   Stream.Emit(0xE, 4);
591   Stream.Emit(0xD, 4);
592
593   // Emit the module.
594   WriteModule(M, Stream);
595   
596   // Write the generated bitstream to "Out".
597   Out.write((char*)&Buffer.front(), Buffer.size());
598 }