add writer support for param attrs
[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->getParamAttrs(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, #pararms, paramty x N]
149       Code = bitc::TYPE_CODE_FUNCTION;
150       TypeVals.push_back(FT->isVarArg());
151       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
152       // FIXME: PARAM ATTR ID!
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       Vals.push_back(NumVarargs);
613       for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
614            i != e; ++i) {
615         Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
616         Vals.push_back(VE.getValueID(I.getOperand(i)));
617       }
618     }
619     break;
620   }
621   case Instruction::Unwind:
622     Code = bitc::FUNC_CODE_INST_UNWIND;
623     break;
624   case Instruction::Unreachable:
625     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
626     break;
627   
628   case Instruction::PHI:
629     Code = bitc::FUNC_CODE_INST_PHI;
630     Vals.push_back(VE.getTypeID(I.getType()));
631     Vals.push_back(I.getNumOperands());
632     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
633       Vals.push_back(VE.getValueID(I.getOperand(i)));
634     break;
635     
636   case Instruction::Malloc:
637     Code = bitc::FUNC_CODE_INST_MALLOC;
638     Vals.push_back(VE.getTypeID(I.getType()));
639     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
640     Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
641     break;
642     
643   case Instruction::Free:
644     Code = bitc::FUNC_CODE_INST_FREE;
645     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
646     Vals.push_back(VE.getValueID(I.getOperand(0)));
647     break;
648     
649   case Instruction::Alloca:
650     Code = bitc::FUNC_CODE_INST_ALLOCA;
651     Vals.push_back(VE.getTypeID(I.getType()));
652     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
653     Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
654     break;
655     
656   case Instruction::Load:
657     Code = bitc::FUNC_CODE_INST_LOAD;
658     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
659     Vals.push_back(VE.getValueID(I.getOperand(0))); // ptr.
660     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
661     Vals.push_back(cast<LoadInst>(I).isVolatile());
662     break;
663   case Instruction::Store:
664     Code = bitc::FUNC_CODE_INST_STORE;
665     Vals.push_back(VE.getTypeID(I.getOperand(1)->getType()));   // Pointer
666     Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
667     Vals.push_back(VE.getValueID(I.getOperand(1))); // ptr.
668     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
669     Vals.push_back(cast<StoreInst>(I).isVolatile());
670     break;
671   case Instruction::Call: {
672     Code = bitc::FUNC_CODE_INST_CALL;
673     Vals.push_back((cast<CallInst>(I).getCallingConv() << 1) |
674                    cast<CallInst>(I).isTailCall());
675     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
676     Vals.push_back(VE.getValueID(I.getOperand(0)));  // callee
677     
678     // Emit value #'s for the fixed parameters.
679     const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
680     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
681     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
682       Vals.push_back(VE.getValueID(I.getOperand(i+1)));  // fixed param.
683       
684     // Emit type/value pairs for varargs params.
685     if (FTy->isVarArg()) {
686       unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
687       for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
688            i != e; ++i) {
689         Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
690         Vals.push_back(VE.getValueID(I.getOperand(i)));
691       }
692     }
693     break;
694   }
695   case Instruction::VAArg:
696     Code = bitc::FUNC_CODE_INST_VAARG;
697     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
698     Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
699     Vals.push_back(VE.getTypeID(I.getType())); // restype.
700     break;
701   }
702   
703   Stream.EmitRecord(Code, Vals, AbbrevToUse);
704   Vals.clear();
705 }
706
707 // Emit names for globals/functions etc.
708 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
709                                   const ValueEnumerator &VE,
710                                   BitstreamWriter &Stream) {
711   if (VST.empty()) return;
712   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 3);
713   
714   // FIXME: Set up the abbrev, we know how many values there are!
715   // FIXME: We know if the type names can use 7-bit ascii.
716   SmallVector<unsigned, 64> NameVals;
717   
718   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
719        SI != SE; ++SI) {
720     unsigned AbbrevToUse = 0;
721     
722     // VST_ENTRY:   [valueid, namelen, namechar x N]
723     // VST_BBENTRY: [bbid, namelen, namechar x N]
724     unsigned Code;
725     if (isa<BasicBlock>(SI->getValue())) {
726       Code = bitc::VST_CODE_BBENTRY;
727     } else {
728       Code = bitc::VST_CODE_ENTRY;
729     }
730     
731     NameVals.push_back(VE.getValueID(SI->getValue()));
732     NameVals.push_back(SI->getKeyLength());
733     for (const char *P = SI->getKeyData(),
734          *E = SI->getKeyData()+SI->getKeyLength(); P != E; ++P)
735       NameVals.push_back((unsigned char)*P);
736     
737     // Emit the finished record.
738     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
739     NameVals.clear();
740   }
741   Stream.ExitBlock();
742 }
743
744 /// WriteFunction - Emit a function body to the module stream.
745 static void WriteFunction(const Function &F, ValueEnumerator &VE, 
746                           BitstreamWriter &Stream) {
747   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 3);
748   VE.incorporateFunction(F);
749
750   SmallVector<unsigned, 64> Vals;
751   
752   // Emit the number of basic blocks, so the reader can create them ahead of
753   // time.
754   Vals.push_back(VE.getBasicBlocks().size());
755   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
756   Vals.clear();
757   
758   // FIXME: Function attributes?
759   
760   // If there are function-local constants, emit them now.
761   unsigned CstStart, CstEnd;
762   VE.getFunctionConstantRange(CstStart, CstEnd);
763   WriteConstants(CstStart, CstEnd, VE, Stream);
764   
765   // Finally, emit all the instructions, in order.
766   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
767     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
768       WriteInstruction(*I, VE, Stream, Vals);
769   
770   // Emit names for all the instructions etc.
771   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
772     
773   VE.purgeFunction();
774   Stream.ExitBlock();
775 }
776
777 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
778 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
779                                  const ValueEnumerator &VE,
780                                  BitstreamWriter &Stream) {
781   if (TST.empty()) return;
782   
783   Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
784   
785   // FIXME: Set up the abbrev, we know how many types there are!
786   // FIXME: We know if the type names can use 7-bit ascii.
787   
788   SmallVector<unsigned, 64> NameVals;
789   
790   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
791        TI != TE; ++TI) {
792     unsigned AbbrevToUse = 0;
793     
794     // TST_ENTRY: [typeid, namelen, namechar x N]
795     NameVals.push_back(VE.getTypeID(TI->second));
796     
797     const std::string &Str = TI->first;
798     NameVals.push_back(Str.size());
799     for (unsigned i = 0, e = Str.size(); i != e; ++i)
800       NameVals.push_back(Str[i]);
801     
802     // Emit the finished record.
803     Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse);
804     NameVals.clear();
805   }
806   
807   Stream.ExitBlock();
808 }
809
810
811 /// WriteModule - Emit the specified module to the bitstream.
812 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
813   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
814   
815   // Emit the version number if it is non-zero.
816   if (CurVersion) {
817     SmallVector<unsigned, 1> Vals;
818     Vals.push_back(CurVersion);
819     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
820   }
821   
822   // Analyze the module, enumerating globals, functions, etc.
823   ValueEnumerator VE(M);
824   
825   // Emit information about parameter attributes.
826   WriteParamAttrTable(VE, Stream);
827   
828   // Emit information describing all of the types in the module.
829   WriteTypeTable(VE, Stream);
830   
831   // Emit top-level description of module, including target triple, inline asm,
832   // descriptors for global variables, and function prototype info.
833   WriteModuleInfo(M, VE, Stream);
834   
835   // Emit constants.
836   WriteModuleConstants(VE, Stream);
837   
838   // If we have any aggregate values in the value table, purge them - these can
839   // only be used to initialize global variables.  Doing so makes the value
840   // namespace smaller for code in functions.
841   int NumNonAggregates = VE.PurgeAggregateValues();
842   if (NumNonAggregates != -1) {
843     SmallVector<unsigned, 1> Vals;
844     Vals.push_back(NumNonAggregates);
845     Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
846   }
847   
848   // Emit function bodies.
849   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
850     if (!I->isDeclaration())
851       WriteFunction(*I, VE, Stream);
852   
853   // Emit the type symbol table information.
854   WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
855   
856   // Emit names for globals/functions etc.
857   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
858   
859   Stream.ExitBlock();
860 }
861
862 /// WriteBitcodeToFile - Write the specified module to the specified output
863 /// stream.
864 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
865   std::vector<unsigned char> Buffer;
866   BitstreamWriter Stream(Buffer);
867   
868   Buffer.reserve(256*1024);
869   
870   // Emit the file header.
871   Stream.Emit((unsigned)'B', 8);
872   Stream.Emit((unsigned)'C', 8);
873   Stream.Emit(0x0, 4);
874   Stream.Emit(0xC, 4);
875   Stream.Emit(0xE, 4);
876   Stream.Emit(0xD, 4);
877
878   // Emit the module.
879   WriteModule(M, Stream);
880   
881   // Write the generated bitstream to "Out".
882   Out.write((char*)&Buffer.front(), Buffer.size());
883 }