[ms-inline asm] Add support for the nsdialect keyword in the Bitcode
[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 is distributed under the University of Illinois Open Source
6 // 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/InlineAsm.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Operator.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Support/Program.h"
31 #include <cctype>
32 #include <map>
33 using namespace llvm;
34
35 static cl::opt<bool>
36 EnablePreserveUseListOrdering("enable-bc-uselist-preserve",
37                               cl::desc("Turn on experimental support for "
38                                        "use-list order preservation."),
39                               cl::init(false), cl::Hidden);
40
41 /// These are manifest constants used by the bitcode writer. They do not need to
42 /// be kept in sync with the reader, but need to be consistent within this file.
43 enum {
44   CurVersion = 0,
45
46   // VALUE_SYMTAB_BLOCK abbrev id's.
47   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
48   VST_ENTRY_7_ABBREV,
49   VST_ENTRY_6_ABBREV,
50   VST_BBENTRY_6_ABBREV,
51
52   // CONSTANTS_BLOCK abbrev id's.
53   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
54   CONSTANTS_INTEGER_ABBREV,
55   CONSTANTS_CE_CAST_Abbrev,
56   CONSTANTS_NULL_Abbrev,
57
58   // FUNCTION_BLOCK abbrev id's.
59   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
60   FUNCTION_INST_BINOP_ABBREV,
61   FUNCTION_INST_BINOP_FLAGS_ABBREV,
62   FUNCTION_INST_CAST_ABBREV,
63   FUNCTION_INST_RET_VOID_ABBREV,
64   FUNCTION_INST_RET_VAL_ABBREV,
65   FUNCTION_INST_UNREACHABLE_ABBREV,
66   
67   // SwitchInst Magic
68   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
69 };
70
71 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
72   switch (Opcode) {
73   default: llvm_unreachable("Unknown cast instruction!");
74   case Instruction::Trunc   : return bitc::CAST_TRUNC;
75   case Instruction::ZExt    : return bitc::CAST_ZEXT;
76   case Instruction::SExt    : return bitc::CAST_SEXT;
77   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
78   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
79   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
80   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
81   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
82   case Instruction::FPExt   : return bitc::CAST_FPEXT;
83   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
84   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
85   case Instruction::BitCast : return bitc::CAST_BITCAST;
86   }
87 }
88
89 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
90   switch (Opcode) {
91   default: llvm_unreachable("Unknown binary instruction!");
92   case Instruction::Add:
93   case Instruction::FAdd: return bitc::BINOP_ADD;
94   case Instruction::Sub:
95   case Instruction::FSub: return bitc::BINOP_SUB;
96   case Instruction::Mul:
97   case Instruction::FMul: return bitc::BINOP_MUL;
98   case Instruction::UDiv: return bitc::BINOP_UDIV;
99   case Instruction::FDiv:
100   case Instruction::SDiv: return bitc::BINOP_SDIV;
101   case Instruction::URem: return bitc::BINOP_UREM;
102   case Instruction::FRem:
103   case Instruction::SRem: return bitc::BINOP_SREM;
104   case Instruction::Shl:  return bitc::BINOP_SHL;
105   case Instruction::LShr: return bitc::BINOP_LSHR;
106   case Instruction::AShr: return bitc::BINOP_ASHR;
107   case Instruction::And:  return bitc::BINOP_AND;
108   case Instruction::Or:   return bitc::BINOP_OR;
109   case Instruction::Xor:  return bitc::BINOP_XOR;
110   }
111 }
112
113 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
114   switch (Op) {
115   default: llvm_unreachable("Unknown RMW operation!");
116   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
117   case AtomicRMWInst::Add: return bitc::RMW_ADD;
118   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
119   case AtomicRMWInst::And: return bitc::RMW_AND;
120   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
121   case AtomicRMWInst::Or: return bitc::RMW_OR;
122   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
123   case AtomicRMWInst::Max: return bitc::RMW_MAX;
124   case AtomicRMWInst::Min: return bitc::RMW_MIN;
125   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
126   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
127   }
128 }
129
130 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
131   switch (Ordering) {
132   case NotAtomic: return bitc::ORDERING_NOTATOMIC;
133   case Unordered: return bitc::ORDERING_UNORDERED;
134   case Monotonic: return bitc::ORDERING_MONOTONIC;
135   case Acquire: return bitc::ORDERING_ACQUIRE;
136   case Release: return bitc::ORDERING_RELEASE;
137   case AcquireRelease: return bitc::ORDERING_ACQREL;
138   case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
139   }
140   llvm_unreachable("Invalid ordering");
141 }
142
143 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
144   switch (SynchScope) {
145   case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
146   case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
147   }
148   llvm_unreachable("Invalid synch scope");
149 }
150
151 static void WriteStringRecord(unsigned Code, StringRef Str,
152                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
153   SmallVector<unsigned, 64> Vals;
154
155   // Code: [strchar x N]
156   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
157     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
158       AbbrevToUse = 0;
159     Vals.push_back(Str[i]);
160   }
161
162   // Emit the finished record.
163   Stream.EmitRecord(Code, Vals, AbbrevToUse);
164 }
165
166 // Emit information about parameter attributes.
167 static void WriteAttributeTable(const ValueEnumerator &VE,
168                                 BitstreamWriter &Stream) {
169   const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
170   if (Attrs.empty()) return;
171
172   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
173
174   SmallVector<uint64_t, 64> Record;
175   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
176     const AttrListPtr &A = Attrs[i];
177     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
178       const AttributeWithIndex &PAWI = A.getSlot(i);
179       Record.push_back(PAWI.Index);
180       Record.push_back(Attribute::encodeLLVMAttributesForBitcode(PAWI.Attrs));
181     }
182
183     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
184     Record.clear();
185   }
186
187   Stream.ExitBlock();
188 }
189
190 /// WriteTypeTable - Write out the type table for a module.
191 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
192   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
193
194   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
195   SmallVector<uint64_t, 64> TypeVals;
196
197   uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
198
199   // Abbrev for TYPE_CODE_POINTER.
200   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
201   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
202   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
203   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
204   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
205
206   // Abbrev for TYPE_CODE_FUNCTION.
207   Abbv = new BitCodeAbbrev();
208   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
209   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
210   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
211   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
212
213   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
214
215   // Abbrev for TYPE_CODE_STRUCT_ANON.
216   Abbv = new BitCodeAbbrev();
217   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
218   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
219   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
220   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
221
222   unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
223
224   // Abbrev for TYPE_CODE_STRUCT_NAME.
225   Abbv = new BitCodeAbbrev();
226   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
227   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
228   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
229   unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
230
231   // Abbrev for TYPE_CODE_STRUCT_NAMED.
232   Abbv = new BitCodeAbbrev();
233   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
234   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
235   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
236   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
237
238   unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
239   
240   // Abbrev for TYPE_CODE_ARRAY.
241   Abbv = new BitCodeAbbrev();
242   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
243   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
244   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
245
246   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
247
248   // Emit an entry count so the reader can reserve space.
249   TypeVals.push_back(TypeList.size());
250   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
251   TypeVals.clear();
252
253   // Loop over all of the types, emitting each in turn.
254   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
255     Type *T = TypeList[i];
256     int AbbrevToUse = 0;
257     unsigned Code = 0;
258
259     switch (T->getTypeID()) {
260     default: llvm_unreachable("Unknown type!");
261     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;   break;
262     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;   break;
263     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;  break;
264     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE; break;
265     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80; break;
266     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128; break;
267     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
268     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;  break;
269     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA; break;
270     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX; break;
271     case Type::IntegerTyID:
272       // INTEGER: [width]
273       Code = bitc::TYPE_CODE_INTEGER;
274       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
275       break;
276     case Type::PointerTyID: {
277       PointerType *PTy = cast<PointerType>(T);
278       // POINTER: [pointee type, address space]
279       Code = bitc::TYPE_CODE_POINTER;
280       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
281       unsigned AddressSpace = PTy->getAddressSpace();
282       TypeVals.push_back(AddressSpace);
283       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
284       break;
285     }
286     case Type::FunctionTyID: {
287       FunctionType *FT = cast<FunctionType>(T);
288       // FUNCTION: [isvararg, retty, paramty x N]
289       Code = bitc::TYPE_CODE_FUNCTION;
290       TypeVals.push_back(FT->isVarArg());
291       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
292       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
293         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
294       AbbrevToUse = FunctionAbbrev;
295       break;
296     }
297     case Type::StructTyID: {
298       StructType *ST = cast<StructType>(T);
299       // STRUCT: [ispacked, eltty x N]
300       TypeVals.push_back(ST->isPacked());
301       // Output all of the element types.
302       for (StructType::element_iterator I = ST->element_begin(),
303            E = ST->element_end(); I != E; ++I)
304         TypeVals.push_back(VE.getTypeID(*I));
305       
306       if (ST->isLiteral()) {
307         Code = bitc::TYPE_CODE_STRUCT_ANON;
308         AbbrevToUse = StructAnonAbbrev;
309       } else {
310         if (ST->isOpaque()) {
311           Code = bitc::TYPE_CODE_OPAQUE;
312         } else {
313           Code = bitc::TYPE_CODE_STRUCT_NAMED;
314           AbbrevToUse = StructNamedAbbrev;
315         }
316
317         // Emit the name if it is present.
318         if (!ST->getName().empty())
319           WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
320                             StructNameAbbrev, Stream);
321       }
322       break;
323     }
324     case Type::ArrayTyID: {
325       ArrayType *AT = cast<ArrayType>(T);
326       // ARRAY: [numelts, eltty]
327       Code = bitc::TYPE_CODE_ARRAY;
328       TypeVals.push_back(AT->getNumElements());
329       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
330       AbbrevToUse = ArrayAbbrev;
331       break;
332     }
333     case Type::VectorTyID: {
334       VectorType *VT = cast<VectorType>(T);
335       // VECTOR [numelts, eltty]
336       Code = bitc::TYPE_CODE_VECTOR;
337       TypeVals.push_back(VT->getNumElements());
338       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
339       break;
340     }
341     }
342
343     // Emit the finished record.
344     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
345     TypeVals.clear();
346   }
347
348   Stream.ExitBlock();
349 }
350
351 static unsigned getEncodedLinkage(const GlobalValue *GV) {
352   switch (GV->getLinkage()) {
353   case GlobalValue::ExternalLinkage:                 return 0;
354   case GlobalValue::WeakAnyLinkage:                  return 1;
355   case GlobalValue::AppendingLinkage:                return 2;
356   case GlobalValue::InternalLinkage:                 return 3;
357   case GlobalValue::LinkOnceAnyLinkage:              return 4;
358   case GlobalValue::DLLImportLinkage:                return 5;
359   case GlobalValue::DLLExportLinkage:                return 6;
360   case GlobalValue::ExternalWeakLinkage:             return 7;
361   case GlobalValue::CommonLinkage:                   return 8;
362   case GlobalValue::PrivateLinkage:                  return 9;
363   case GlobalValue::WeakODRLinkage:                  return 10;
364   case GlobalValue::LinkOnceODRLinkage:              return 11;
365   case GlobalValue::AvailableExternallyLinkage:      return 12;
366   case GlobalValue::LinkerPrivateLinkage:            return 13;
367   case GlobalValue::LinkerPrivateWeakLinkage:        return 14;
368   case GlobalValue::LinkOnceODRAutoHideLinkage:      return 15;
369   }
370   llvm_unreachable("Invalid linkage");
371 }
372
373 static unsigned getEncodedVisibility(const GlobalValue *GV) {
374   switch (GV->getVisibility()) {
375   case GlobalValue::DefaultVisibility:   return 0;
376   case GlobalValue::HiddenVisibility:    return 1;
377   case GlobalValue::ProtectedVisibility: return 2;
378   }
379   llvm_unreachable("Invalid visibility");
380 }
381
382 static unsigned getEncodedThreadLocalMode(const GlobalVariable *GV) {
383   switch (GV->getThreadLocalMode()) {
384     case GlobalVariable::NotThreadLocal:         return 0;
385     case GlobalVariable::GeneralDynamicTLSModel: return 1;
386     case GlobalVariable::LocalDynamicTLSModel:   return 2;
387     case GlobalVariable::InitialExecTLSModel:    return 3;
388     case GlobalVariable::LocalExecTLSModel:      return 4;
389   }
390   llvm_unreachable("Invalid TLS model");
391 }
392
393 // Emit top-level description of module, including target triple, inline asm,
394 // descriptors for global variables, and function prototype info.
395 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
396                             BitstreamWriter &Stream) {
397   // Emit the list of dependent libraries for the Module.
398   for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
399     WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
400
401   // Emit various pieces of data attached to a module.
402   if (!M->getTargetTriple().empty())
403     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
404                       0/*TODO*/, Stream);
405   if (!M->getDataLayout().empty())
406     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
407                       0/*TODO*/, Stream);
408   if (!M->getModuleInlineAsm().empty())
409     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
410                       0/*TODO*/, Stream);
411
412   // Emit information about sections and GC, computing how many there are. Also
413   // compute the maximum alignment value.
414   std::map<std::string, unsigned> SectionMap;
415   std::map<std::string, unsigned> GCMap;
416   unsigned MaxAlignment = 0;
417   unsigned MaxGlobalType = 0;
418   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
419        GV != E; ++GV) {
420     MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
421     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
422     if (GV->hasSection()) {
423       // Give section names unique ID's.
424       unsigned &Entry = SectionMap[GV->getSection()];
425       if (!Entry) {
426         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
427                           0/*TODO*/, Stream);
428         Entry = SectionMap.size();
429       }
430     }
431   }
432   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
433     MaxAlignment = std::max(MaxAlignment, F->getAlignment());
434     if (F->hasSection()) {
435       // Give section names unique ID's.
436       unsigned &Entry = SectionMap[F->getSection()];
437       if (!Entry) {
438         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
439                           0/*TODO*/, Stream);
440         Entry = SectionMap.size();
441       }
442     }
443     if (F->hasGC()) {
444       // Same for GC names.
445       unsigned &Entry = GCMap[F->getGC()];
446       if (!Entry) {
447         WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
448                           0/*TODO*/, Stream);
449         Entry = GCMap.size();
450       }
451     }
452   }
453
454   // Emit abbrev for globals, now that we know # sections and max alignment.
455   unsigned SimpleGVarAbbrev = 0;
456   if (!M->global_empty()) {
457     // Add an abbrev for common globals with no visibility or thread localness.
458     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
459     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
460     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
461                               Log2_32_Ceil(MaxGlobalType+1)));
462     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
463     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
464     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));      // Linkage.
465     if (MaxAlignment == 0)                                      // Alignment.
466       Abbv->Add(BitCodeAbbrevOp(0));
467     else {
468       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
469       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
470                                Log2_32_Ceil(MaxEncAlignment+1)));
471     }
472     if (SectionMap.empty())                                    // Section.
473       Abbv->Add(BitCodeAbbrevOp(0));
474     else
475       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
476                                Log2_32_Ceil(SectionMap.size()+1)));
477     // Don't bother emitting vis + thread local.
478     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
479   }
480
481   // Emit the global variable information.
482   SmallVector<unsigned, 64> Vals;
483   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
484        GV != E; ++GV) {
485     unsigned AbbrevToUse = 0;
486
487     // GLOBALVAR: [type, isconst, initid,
488     //             linkage, alignment, section, visibility, threadlocal,
489     //             unnamed_addr]
490     Vals.push_back(VE.getTypeID(GV->getType()));
491     Vals.push_back(GV->isConstant());
492     Vals.push_back(GV->isDeclaration() ? 0 :
493                    (VE.getValueID(GV->getInitializer()) + 1));
494     Vals.push_back(getEncodedLinkage(GV));
495     Vals.push_back(Log2_32(GV->getAlignment())+1);
496     Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
497     if (GV->isThreadLocal() ||
498         GV->getVisibility() != GlobalValue::DefaultVisibility ||
499         GV->hasUnnamedAddr()) {
500       Vals.push_back(getEncodedVisibility(GV));
501       Vals.push_back(getEncodedThreadLocalMode(GV));
502       Vals.push_back(GV->hasUnnamedAddr());
503     } else {
504       AbbrevToUse = SimpleGVarAbbrev;
505     }
506
507     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
508     Vals.clear();
509   }
510
511   // Emit the function proto information.
512   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
513     // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignment,
514     //             section, visibility, gc, unnamed_addr]
515     Vals.push_back(VE.getTypeID(F->getType()));
516     Vals.push_back(F->getCallingConv());
517     Vals.push_back(F->isDeclaration());
518     Vals.push_back(getEncodedLinkage(F));
519     Vals.push_back(VE.getAttributeID(F->getAttributes()));
520     Vals.push_back(Log2_32(F->getAlignment())+1);
521     Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
522     Vals.push_back(getEncodedVisibility(F));
523     Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
524     Vals.push_back(F->hasUnnamedAddr());
525
526     unsigned AbbrevToUse = 0;
527     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
528     Vals.clear();
529   }
530
531   // Emit the alias information.
532   for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
533        AI != E; ++AI) {
534     // ALIAS: [alias type, aliasee val#, linkage, visibility]
535     Vals.push_back(VE.getTypeID(AI->getType()));
536     Vals.push_back(VE.getValueID(AI->getAliasee()));
537     Vals.push_back(getEncodedLinkage(AI));
538     Vals.push_back(getEncodedVisibility(AI));
539     unsigned AbbrevToUse = 0;
540     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
541     Vals.clear();
542   }
543 }
544
545 static uint64_t GetOptimizationFlags(const Value *V) {
546   uint64_t Flags = 0;
547
548   if (const OverflowingBinaryOperator *OBO =
549         dyn_cast<OverflowingBinaryOperator>(V)) {
550     if (OBO->hasNoSignedWrap())
551       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
552     if (OBO->hasNoUnsignedWrap())
553       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
554   } else if (const PossiblyExactOperator *PEO =
555                dyn_cast<PossiblyExactOperator>(V)) {
556     if (PEO->isExact())
557       Flags |= 1 << bitc::PEO_EXACT;
558   }
559
560   return Flags;
561 }
562
563 static void WriteMDNode(const MDNode *N,
564                         const ValueEnumerator &VE,
565                         BitstreamWriter &Stream,
566                         SmallVector<uint64_t, 64> &Record) {
567   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
568     if (N->getOperand(i)) {
569       Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
570       Record.push_back(VE.getValueID(N->getOperand(i)));
571     } else {
572       Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
573       Record.push_back(0);
574     }
575   }
576   unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
577                                            bitc::METADATA_NODE;
578   Stream.EmitRecord(MDCode, Record, 0);
579   Record.clear();
580 }
581
582 static void WriteModuleMetadata(const Module *M,
583                                 const ValueEnumerator &VE,
584                                 BitstreamWriter &Stream) {
585   const ValueEnumerator::ValueList &Vals = VE.getMDValues();
586   bool StartedMetadataBlock = false;
587   unsigned MDSAbbrev = 0;
588   SmallVector<uint64_t, 64> Record;
589   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
590
591     if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
592       if (!N->isFunctionLocal() || !N->getFunction()) {
593         if (!StartedMetadataBlock) {
594           Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
595           StartedMetadataBlock = true;
596         }
597         WriteMDNode(N, VE, Stream, Record);
598       }
599     } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
600       if (!StartedMetadataBlock)  {
601         Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
602
603         // Abbrev for METADATA_STRING.
604         BitCodeAbbrev *Abbv = new BitCodeAbbrev();
605         Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
606         Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
607         Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
608         MDSAbbrev = Stream.EmitAbbrev(Abbv);
609         StartedMetadataBlock = true;
610       }
611
612       // Code: [strchar x N]
613       Record.append(MDS->begin(), MDS->end());
614
615       // Emit the finished record.
616       Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
617       Record.clear();
618     }
619   }
620
621   // Write named metadata.
622   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
623        E = M->named_metadata_end(); I != E; ++I) {
624     const NamedMDNode *NMD = I;
625     if (!StartedMetadataBlock)  {
626       Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
627       StartedMetadataBlock = true;
628     }
629
630     // Write name.
631     StringRef Str = NMD->getName();
632     for (unsigned i = 0, e = Str.size(); i != e; ++i)
633       Record.push_back(Str[i]);
634     Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
635     Record.clear();
636
637     // Write named metadata operands.
638     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
639       Record.push_back(VE.getValueID(NMD->getOperand(i)));
640     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
641     Record.clear();
642   }
643
644   if (StartedMetadataBlock)
645     Stream.ExitBlock();
646 }
647
648 static void WriteFunctionLocalMetadata(const Function &F,
649                                        const ValueEnumerator &VE,
650                                        BitstreamWriter &Stream) {
651   bool StartedMetadataBlock = false;
652   SmallVector<uint64_t, 64> Record;
653   const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues();
654   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
655     if (const MDNode *N = Vals[i])
656       if (N->isFunctionLocal() && N->getFunction() == &F) {
657         if (!StartedMetadataBlock) {
658           Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
659           StartedMetadataBlock = true;
660         }
661         WriteMDNode(N, VE, Stream, Record);
662       }
663       
664   if (StartedMetadataBlock)
665     Stream.ExitBlock();
666 }
667
668 static void WriteMetadataAttachment(const Function &F,
669                                     const ValueEnumerator &VE,
670                                     BitstreamWriter &Stream) {
671   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
672
673   SmallVector<uint64_t, 64> Record;
674
675   // Write metadata attachments
676   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
677   SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
678   
679   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
680     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
681          I != E; ++I) {
682       MDs.clear();
683       I->getAllMetadataOtherThanDebugLoc(MDs);
684       
685       // If no metadata, ignore instruction.
686       if (MDs.empty()) continue;
687
688       Record.push_back(VE.getInstructionID(I));
689       
690       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
691         Record.push_back(MDs[i].first);
692         Record.push_back(VE.getValueID(MDs[i].second));
693       }
694       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
695       Record.clear();
696     }
697
698   Stream.ExitBlock();
699 }
700
701 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
702   SmallVector<uint64_t, 64> Record;
703
704   // Write metadata kinds
705   // METADATA_KIND - [n x [id, name]]
706   SmallVector<StringRef, 4> Names;
707   M->getMDKindNames(Names);
708   
709   if (Names.empty()) return;
710
711   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
712   
713   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
714     Record.push_back(MDKindID);
715     StringRef KName = Names[MDKindID];
716     Record.append(KName.begin(), KName.end());
717     
718     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
719     Record.clear();
720   }
721
722   Stream.ExitBlock();
723 }
724
725 static void EmitAPInt(SmallVectorImpl<uint64_t> &Vals,
726                       unsigned &Code, unsigned &AbbrevToUse, const APInt &Val,
727                       bool EmitSizeForWideNumbers = false
728                       ) {
729   if (Val.getBitWidth() <= 64) {
730     uint64_t V = Val.getSExtValue();
731     if ((int64_t)V >= 0)
732       Vals.push_back(V << 1);
733     else
734       Vals.push_back((-V << 1) | 1);
735     Code = bitc::CST_CODE_INTEGER;
736     AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
737   } else {
738     // Wide integers, > 64 bits in size.
739     // We have an arbitrary precision integer value to write whose
740     // bit width is > 64. However, in canonical unsigned integer
741     // format it is likely that the high bits are going to be zero.
742     // So, we only write the number of active words.
743     unsigned NWords = Val.getActiveWords();
744     
745     if (EmitSizeForWideNumbers)
746       Vals.push_back(NWords);
747     
748     const uint64_t *RawWords = Val.getRawData();
749     for (unsigned i = 0; i != NWords; ++i) {
750       int64_t V = RawWords[i];
751       if (V >= 0)
752         Vals.push_back(V << 1);
753       else
754         Vals.push_back((-V << 1) | 1);
755     }
756     Code = bitc::CST_CODE_WIDE_INTEGER;
757   }
758 }
759
760 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
761                            const ValueEnumerator &VE,
762                            BitstreamWriter &Stream, bool isGlobal) {
763   if (FirstVal == LastVal) return;
764
765   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
766
767   unsigned AggregateAbbrev = 0;
768   unsigned String8Abbrev = 0;
769   unsigned CString7Abbrev = 0;
770   unsigned CString6Abbrev = 0;
771   // If this is a constant pool for the module, emit module-specific abbrevs.
772   if (isGlobal) {
773     // Abbrev for CST_CODE_AGGREGATE.
774     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
775     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
776     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
777     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
778     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
779
780     // Abbrev for CST_CODE_STRING.
781     Abbv = new BitCodeAbbrev();
782     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
783     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
784     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
785     String8Abbrev = Stream.EmitAbbrev(Abbv);
786     // Abbrev for CST_CODE_CSTRING.
787     Abbv = new BitCodeAbbrev();
788     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
789     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
790     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
791     CString7Abbrev = Stream.EmitAbbrev(Abbv);
792     // Abbrev for CST_CODE_CSTRING.
793     Abbv = new BitCodeAbbrev();
794     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
795     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
796     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
797     CString6Abbrev = Stream.EmitAbbrev(Abbv);
798   }
799
800   SmallVector<uint64_t, 64> Record;
801
802   const ValueEnumerator::ValueList &Vals = VE.getValues();
803   Type *LastTy = 0;
804   for (unsigned i = FirstVal; i != LastVal; ++i) {
805     const Value *V = Vals[i].first;
806     // If we need to switch types, do so now.
807     if (V->getType() != LastTy) {
808       LastTy = V->getType();
809       Record.push_back(VE.getTypeID(LastTy));
810       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
811                         CONSTANTS_SETTYPE_ABBREV);
812       Record.clear();
813     }
814
815     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
816       Record.push_back(unsigned(IA->hasSideEffects()) |
817                        unsigned(IA->isAlignStack()) << 1 |
818                        unsigned(IA->getDialect()&1) << 2);
819
820       // Add the asm string.
821       const std::string &AsmStr = IA->getAsmString();
822       Record.push_back(AsmStr.size());
823       for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
824         Record.push_back(AsmStr[i]);
825
826       // Add the constraint string.
827       const std::string &ConstraintStr = IA->getConstraintString();
828       Record.push_back(ConstraintStr.size());
829       for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
830         Record.push_back(ConstraintStr[i]);
831       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
832       Record.clear();
833       continue;
834     }
835     const Constant *C = cast<Constant>(V);
836     unsigned Code = -1U;
837     unsigned AbbrevToUse = 0;
838     if (C->isNullValue()) {
839       Code = bitc::CST_CODE_NULL;
840     } else if (isa<UndefValue>(C)) {
841       Code = bitc::CST_CODE_UNDEF;
842     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
843       EmitAPInt(Record, Code, AbbrevToUse, IV->getValue());
844     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
845       Code = bitc::CST_CODE_FLOAT;
846       Type *Ty = CFP->getType();
847       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
848         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
849       } else if (Ty->isX86_FP80Ty()) {
850         // api needed to prevent premature destruction
851         // bits are not in the same order as a normal i80 APInt, compensate.
852         APInt api = CFP->getValueAPF().bitcastToAPInt();
853         const uint64_t *p = api.getRawData();
854         Record.push_back((p[1] << 48) | (p[0] >> 16));
855         Record.push_back(p[0] & 0xffffLL);
856       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
857         APInt api = CFP->getValueAPF().bitcastToAPInt();
858         const uint64_t *p = api.getRawData();
859         Record.push_back(p[0]);
860         Record.push_back(p[1]);
861       } else {
862         assert (0 && "Unknown FP type!");
863       }
864     } else if (isa<ConstantDataSequential>(C) &&
865                cast<ConstantDataSequential>(C)->isString()) {
866       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
867       // Emit constant strings specially.
868       unsigned NumElts = Str->getNumElements();
869       // If this is a null-terminated string, use the denser CSTRING encoding.
870       if (Str->isCString()) {
871         Code = bitc::CST_CODE_CSTRING;
872         --NumElts;  // Don't encode the null, which isn't allowed by char6.
873       } else {
874         Code = bitc::CST_CODE_STRING;
875         AbbrevToUse = String8Abbrev;
876       }
877       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
878       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
879       for (unsigned i = 0; i != NumElts; ++i) {
880         unsigned char V = Str->getElementAsInteger(i);
881         Record.push_back(V);
882         isCStr7 &= (V & 128) == 0;
883         if (isCStrChar6)
884           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
885       }
886       
887       if (isCStrChar6)
888         AbbrevToUse = CString6Abbrev;
889       else if (isCStr7)
890         AbbrevToUse = CString7Abbrev;
891     } else if (const ConstantDataSequential *CDS = 
892                   dyn_cast<ConstantDataSequential>(C)) {
893       Code = bitc::CST_CODE_DATA;
894       Type *EltTy = CDS->getType()->getElementType();
895       if (isa<IntegerType>(EltTy)) {
896         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
897           Record.push_back(CDS->getElementAsInteger(i));
898       } else if (EltTy->isFloatTy()) {
899         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
900           union { float F; uint32_t I; };
901           F = CDS->getElementAsFloat(i);
902           Record.push_back(I);
903         }
904       } else {
905         assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
906         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
907           union { double F; uint64_t I; };
908           F = CDS->getElementAsDouble(i);
909           Record.push_back(I);
910         }
911       }
912     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
913                isa<ConstantVector>(C)) {
914       Code = bitc::CST_CODE_AGGREGATE;
915       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
916         Record.push_back(VE.getValueID(C->getOperand(i)));
917       AbbrevToUse = AggregateAbbrev;
918     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
919       switch (CE->getOpcode()) {
920       default:
921         if (Instruction::isCast(CE->getOpcode())) {
922           Code = bitc::CST_CODE_CE_CAST;
923           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
924           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
925           Record.push_back(VE.getValueID(C->getOperand(0)));
926           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
927         } else {
928           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
929           Code = bitc::CST_CODE_CE_BINOP;
930           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
931           Record.push_back(VE.getValueID(C->getOperand(0)));
932           Record.push_back(VE.getValueID(C->getOperand(1)));
933           uint64_t Flags = GetOptimizationFlags(CE);
934           if (Flags != 0)
935             Record.push_back(Flags);
936         }
937         break;
938       case Instruction::GetElementPtr:
939         Code = bitc::CST_CODE_CE_GEP;
940         if (cast<GEPOperator>(C)->isInBounds())
941           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
942         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
943           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
944           Record.push_back(VE.getValueID(C->getOperand(i)));
945         }
946         break;
947       case Instruction::Select:
948         Code = bitc::CST_CODE_CE_SELECT;
949         Record.push_back(VE.getValueID(C->getOperand(0)));
950         Record.push_back(VE.getValueID(C->getOperand(1)));
951         Record.push_back(VE.getValueID(C->getOperand(2)));
952         break;
953       case Instruction::ExtractElement:
954         Code = bitc::CST_CODE_CE_EXTRACTELT;
955         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
956         Record.push_back(VE.getValueID(C->getOperand(0)));
957         Record.push_back(VE.getValueID(C->getOperand(1)));
958         break;
959       case Instruction::InsertElement:
960         Code = bitc::CST_CODE_CE_INSERTELT;
961         Record.push_back(VE.getValueID(C->getOperand(0)));
962         Record.push_back(VE.getValueID(C->getOperand(1)));
963         Record.push_back(VE.getValueID(C->getOperand(2)));
964         break;
965       case Instruction::ShuffleVector:
966         // If the return type and argument types are the same, this is a
967         // standard shufflevector instruction.  If the types are different,
968         // then the shuffle is widening or truncating the input vectors, and
969         // the argument type must also be encoded.
970         if (C->getType() == C->getOperand(0)->getType()) {
971           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
972         } else {
973           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
974           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
975         }
976         Record.push_back(VE.getValueID(C->getOperand(0)));
977         Record.push_back(VE.getValueID(C->getOperand(1)));
978         Record.push_back(VE.getValueID(C->getOperand(2)));
979         break;
980       case Instruction::ICmp:
981       case Instruction::FCmp:
982         Code = bitc::CST_CODE_CE_CMP;
983         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
984         Record.push_back(VE.getValueID(C->getOperand(0)));
985         Record.push_back(VE.getValueID(C->getOperand(1)));
986         Record.push_back(CE->getPredicate());
987         break;
988       }
989     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
990       Code = bitc::CST_CODE_BLOCKADDRESS;
991       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
992       Record.push_back(VE.getValueID(BA->getFunction()));
993       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
994     } else {
995 #ifndef NDEBUG
996       C->dump();
997 #endif
998       llvm_unreachable("Unknown constant!");
999     }
1000     Stream.EmitRecord(Code, Record, AbbrevToUse);
1001     Record.clear();
1002   }
1003
1004   Stream.ExitBlock();
1005 }
1006
1007 static void WriteModuleConstants(const ValueEnumerator &VE,
1008                                  BitstreamWriter &Stream) {
1009   const ValueEnumerator::ValueList &Vals = VE.getValues();
1010
1011   // Find the first constant to emit, which is the first non-globalvalue value.
1012   // We know globalvalues have been emitted by WriteModuleInfo.
1013   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1014     if (!isa<GlobalValue>(Vals[i].first)) {
1015       WriteConstants(i, Vals.size(), VE, Stream, true);
1016       return;
1017     }
1018   }
1019 }
1020
1021 /// PushValueAndType - The file has to encode both the value and type id for
1022 /// many values, because we need to know what type to create for forward
1023 /// references.  However, most operands are not forward references, so this type
1024 /// field is not needed.
1025 ///
1026 /// This function adds V's value ID to Vals.  If the value ID is higher than the
1027 /// instruction ID, then it is a forward reference, and it also includes the
1028 /// type ID.
1029 static bool PushValueAndType(const Value *V, unsigned InstID,
1030                              SmallVector<unsigned, 64> &Vals,
1031                              ValueEnumerator &VE) {
1032   unsigned ValID = VE.getValueID(V);
1033   Vals.push_back(ValID);
1034   if (ValID >= InstID) {
1035     Vals.push_back(VE.getTypeID(V->getType()));
1036     return true;
1037   }
1038   return false;
1039 }
1040
1041 /// WriteInstruction - Emit an instruction to the specified stream.
1042 static void WriteInstruction(const Instruction &I, unsigned InstID,
1043                              ValueEnumerator &VE, BitstreamWriter &Stream,
1044                              SmallVector<unsigned, 64> &Vals) {
1045   unsigned Code = 0;
1046   unsigned AbbrevToUse = 0;
1047   VE.setInstructionID(&I);
1048   switch (I.getOpcode()) {
1049   default:
1050     if (Instruction::isCast(I.getOpcode())) {
1051       Code = bitc::FUNC_CODE_INST_CAST;
1052       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1053         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1054       Vals.push_back(VE.getTypeID(I.getType()));
1055       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1056     } else {
1057       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1058       Code = bitc::FUNC_CODE_INST_BINOP;
1059       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1060         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1061       Vals.push_back(VE.getValueID(I.getOperand(1)));
1062       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1063       uint64_t Flags = GetOptimizationFlags(&I);
1064       if (Flags != 0) {
1065         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1066           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1067         Vals.push_back(Flags);
1068       }
1069     }
1070     break;
1071
1072   case Instruction::GetElementPtr:
1073     Code = bitc::FUNC_CODE_INST_GEP;
1074     if (cast<GEPOperator>(&I)->isInBounds())
1075       Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1076     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1077       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1078     break;
1079   case Instruction::ExtractValue: {
1080     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1081     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1082     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1083     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1084       Vals.push_back(*i);
1085     break;
1086   }
1087   case Instruction::InsertValue: {
1088     Code = bitc::FUNC_CODE_INST_INSERTVAL;
1089     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1090     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1091     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1092     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1093       Vals.push_back(*i);
1094     break;
1095   }
1096   case Instruction::Select:
1097     Code = bitc::FUNC_CODE_INST_VSELECT;
1098     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1099     Vals.push_back(VE.getValueID(I.getOperand(2)));
1100     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1101     break;
1102   case Instruction::ExtractElement:
1103     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1104     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1105     Vals.push_back(VE.getValueID(I.getOperand(1)));
1106     break;
1107   case Instruction::InsertElement:
1108     Code = bitc::FUNC_CODE_INST_INSERTELT;
1109     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1110     Vals.push_back(VE.getValueID(I.getOperand(1)));
1111     Vals.push_back(VE.getValueID(I.getOperand(2)));
1112     break;
1113   case Instruction::ShuffleVector:
1114     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1115     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1116     Vals.push_back(VE.getValueID(I.getOperand(1)));
1117     Vals.push_back(VE.getValueID(I.getOperand(2)));
1118     break;
1119   case Instruction::ICmp:
1120   case Instruction::FCmp:
1121     // compare returning Int1Ty or vector of Int1Ty
1122     Code = bitc::FUNC_CODE_INST_CMP2;
1123     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1124     Vals.push_back(VE.getValueID(I.getOperand(1)));
1125     Vals.push_back(cast<CmpInst>(I).getPredicate());
1126     break;
1127
1128   case Instruction::Ret:
1129     {
1130       Code = bitc::FUNC_CODE_INST_RET;
1131       unsigned NumOperands = I.getNumOperands();
1132       if (NumOperands == 0)
1133         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1134       else if (NumOperands == 1) {
1135         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1136           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1137       } else {
1138         for (unsigned i = 0, e = NumOperands; i != e; ++i)
1139           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1140       }
1141     }
1142     break;
1143   case Instruction::Br:
1144     {
1145       Code = bitc::FUNC_CODE_INST_BR;
1146       BranchInst &II = cast<BranchInst>(I);
1147       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1148       if (II.isConditional()) {
1149         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1150         Vals.push_back(VE.getValueID(II.getCondition()));
1151       }
1152     }
1153     break;
1154   case Instruction::Switch:
1155     {
1156       // Redefine Vals, since here we need to use 64 bit values
1157       // explicitly to store large APInt numbers.
1158       SmallVector<uint64_t, 128> Vals64;
1159       
1160       Code = bitc::FUNC_CODE_INST_SWITCH;
1161       SwitchInst &SI = cast<SwitchInst>(I);
1162       
1163       uint32_t SwitchRecordHeader = SI.hash() | (SWITCH_INST_MAGIC << 16); 
1164       Vals64.push_back(SwitchRecordHeader);      
1165       
1166       Vals64.push_back(VE.getTypeID(SI.getCondition()->getType()));
1167       Vals64.push_back(VE.getValueID(SI.getCondition()));
1168       Vals64.push_back(VE.getValueID(SI.getDefaultDest()));
1169       Vals64.push_back(SI.getNumCases());
1170       for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
1171            i != e; ++i) {
1172         IntegersSubset& CaseRanges = i.getCaseValueEx();
1173         unsigned Code, Abbrev; // will unused.
1174         
1175         if (CaseRanges.isSingleNumber()) {
1176           Vals64.push_back(1/*NumItems = 1*/);
1177           Vals64.push_back(true/*IsSingleNumber = true*/);
1178           EmitAPInt(Vals64, Code, Abbrev, CaseRanges.getSingleNumber(0), true);
1179         } else {
1180           
1181           Vals64.push_back(CaseRanges.getNumItems());
1182           
1183           if (CaseRanges.isSingleNumbersOnly()) {
1184             for (unsigned ri = 0, rn = CaseRanges.getNumItems();
1185                  ri != rn; ++ri) {
1186               
1187               Vals64.push_back(true/*IsSingleNumber = true*/);
1188               
1189               EmitAPInt(Vals64, Code, Abbrev,
1190                         CaseRanges.getSingleNumber(ri), true);
1191             }
1192           } else
1193             for (unsigned ri = 0, rn = CaseRanges.getNumItems();
1194                  ri != rn; ++ri) {
1195               IntegersSubset::Range r = CaseRanges.getItem(ri);
1196               bool IsSingleNumber = CaseRanges.isSingleNumber(ri);
1197     
1198               Vals64.push_back(IsSingleNumber);
1199               
1200               EmitAPInt(Vals64, Code, Abbrev, r.getLow(), true);
1201               if (!IsSingleNumber)
1202                 EmitAPInt(Vals64, Code, Abbrev, r.getHigh(), true);
1203             }
1204         }
1205         Vals64.push_back(VE.getValueID(i.getCaseSuccessor()));
1206       }
1207       
1208       Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1209       
1210       // Also do expected action - clear external Vals collection:
1211       Vals.clear();
1212       return;
1213     }
1214     break;
1215   case Instruction::IndirectBr:
1216     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1217     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1218     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1219       Vals.push_back(VE.getValueID(I.getOperand(i)));
1220     break;
1221       
1222   case Instruction::Invoke: {
1223     const InvokeInst *II = cast<InvokeInst>(&I);
1224     const Value *Callee(II->getCalledValue());
1225     PointerType *PTy = cast<PointerType>(Callee->getType());
1226     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1227     Code = bitc::FUNC_CODE_INST_INVOKE;
1228
1229     Vals.push_back(VE.getAttributeID(II->getAttributes()));
1230     Vals.push_back(II->getCallingConv());
1231     Vals.push_back(VE.getValueID(II->getNormalDest()));
1232     Vals.push_back(VE.getValueID(II->getUnwindDest()));
1233     PushValueAndType(Callee, InstID, Vals, VE);
1234
1235     // Emit value #'s for the fixed parameters.
1236     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1237       Vals.push_back(VE.getValueID(I.getOperand(i)));  // fixed param.
1238
1239     // Emit type/value pairs for varargs params.
1240     if (FTy->isVarArg()) {
1241       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1242            i != e; ++i)
1243         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1244     }
1245     break;
1246   }
1247   case Instruction::Resume:
1248     Code = bitc::FUNC_CODE_INST_RESUME;
1249     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1250     break;
1251   case Instruction::Unreachable:
1252     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1253     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1254     break;
1255
1256   case Instruction::PHI: {
1257     const PHINode &PN = cast<PHINode>(I);
1258     Code = bitc::FUNC_CODE_INST_PHI;
1259     Vals.push_back(VE.getTypeID(PN.getType()));
1260     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1261       Vals.push_back(VE.getValueID(PN.getIncomingValue(i)));
1262       Vals.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1263     }
1264     break;
1265   }
1266
1267   case Instruction::LandingPad: {
1268     const LandingPadInst &LP = cast<LandingPadInst>(I);
1269     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1270     Vals.push_back(VE.getTypeID(LP.getType()));
1271     PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1272     Vals.push_back(LP.isCleanup());
1273     Vals.push_back(LP.getNumClauses());
1274     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1275       if (LP.isCatch(I))
1276         Vals.push_back(LandingPadInst::Catch);
1277       else
1278         Vals.push_back(LandingPadInst::Filter);
1279       PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1280     }
1281     break;
1282   }
1283
1284   case Instruction::Alloca:
1285     Code = bitc::FUNC_CODE_INST_ALLOCA;
1286     Vals.push_back(VE.getTypeID(I.getType()));
1287     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1288     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1289     Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1290     break;
1291
1292   case Instruction::Load:
1293     if (cast<LoadInst>(I).isAtomic()) {
1294       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1295       PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1296     } else {
1297       Code = bitc::FUNC_CODE_INST_LOAD;
1298       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
1299         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1300     }
1301     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1302     Vals.push_back(cast<LoadInst>(I).isVolatile());
1303     if (cast<LoadInst>(I).isAtomic()) {
1304       Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1305       Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1306     }
1307     break;
1308   case Instruction::Store:
1309     if (cast<StoreInst>(I).isAtomic())
1310       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1311     else
1312       Code = bitc::FUNC_CODE_INST_STORE;
1313     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
1314     Vals.push_back(VE.getValueID(I.getOperand(0)));       // val.
1315     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1316     Vals.push_back(cast<StoreInst>(I).isVolatile());
1317     if (cast<StoreInst>(I).isAtomic()) {
1318       Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1319       Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1320     }
1321     break;
1322   case Instruction::AtomicCmpXchg:
1323     Code = bitc::FUNC_CODE_INST_CMPXCHG;
1324     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
1325     Vals.push_back(VE.getValueID(I.getOperand(1)));       // cmp.
1326     Vals.push_back(VE.getValueID(I.getOperand(2)));       // newval.
1327     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1328     Vals.push_back(GetEncodedOrdering(
1329                      cast<AtomicCmpXchgInst>(I).getOrdering()));
1330     Vals.push_back(GetEncodedSynchScope(
1331                      cast<AtomicCmpXchgInst>(I).getSynchScope()));
1332     break;
1333   case Instruction::AtomicRMW:
1334     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1335     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
1336     Vals.push_back(VE.getValueID(I.getOperand(1)));       // val.
1337     Vals.push_back(GetEncodedRMWOperation(
1338                      cast<AtomicRMWInst>(I).getOperation()));
1339     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1340     Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1341     Vals.push_back(GetEncodedSynchScope(
1342                      cast<AtomicRMWInst>(I).getSynchScope()));
1343     break;
1344   case Instruction::Fence:
1345     Code = bitc::FUNC_CODE_INST_FENCE;
1346     Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1347     Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1348     break;
1349   case Instruction::Call: {
1350     const CallInst &CI = cast<CallInst>(I);
1351     PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1352     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1353
1354     Code = bitc::FUNC_CODE_INST_CALL;
1355
1356     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1357     Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1358     PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
1359
1360     // Emit value #'s for the fixed parameters.
1361     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1362       Vals.push_back(VE.getValueID(CI.getArgOperand(i)));  // fixed param.
1363
1364     // Emit type/value pairs for varargs params.
1365     if (FTy->isVarArg()) {
1366       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1367            i != e; ++i)
1368         PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
1369     }
1370     break;
1371   }
1372   case Instruction::VAArg:
1373     Code = bitc::FUNC_CODE_INST_VAARG;
1374     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
1375     Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
1376     Vals.push_back(VE.getTypeID(I.getType())); // restype.
1377     break;
1378   }
1379
1380   Stream.EmitRecord(Code, Vals, AbbrevToUse);
1381   Vals.clear();
1382 }
1383
1384 // Emit names for globals/functions etc.
1385 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1386                                   const ValueEnumerator &VE,
1387                                   BitstreamWriter &Stream) {
1388   if (VST.empty()) return;
1389   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1390
1391   // FIXME: Set up the abbrev, we know how many values there are!
1392   // FIXME: We know if the type names can use 7-bit ascii.
1393   SmallVector<unsigned, 64> NameVals;
1394
1395   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1396        SI != SE; ++SI) {
1397
1398     const ValueName &Name = *SI;
1399
1400     // Figure out the encoding to use for the name.
1401     bool is7Bit = true;
1402     bool isChar6 = true;
1403     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1404          C != E; ++C) {
1405       if (isChar6)
1406         isChar6 = BitCodeAbbrevOp::isChar6(*C);
1407       if ((unsigned char)*C & 128) {
1408         is7Bit = false;
1409         break;  // don't bother scanning the rest.
1410       }
1411     }
1412
1413     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1414
1415     // VST_ENTRY:   [valueid, namechar x N]
1416     // VST_BBENTRY: [bbid, namechar x N]
1417     unsigned Code;
1418     if (isa<BasicBlock>(SI->getValue())) {
1419       Code = bitc::VST_CODE_BBENTRY;
1420       if (isChar6)
1421         AbbrevToUse = VST_BBENTRY_6_ABBREV;
1422     } else {
1423       Code = bitc::VST_CODE_ENTRY;
1424       if (isChar6)
1425         AbbrevToUse = VST_ENTRY_6_ABBREV;
1426       else if (is7Bit)
1427         AbbrevToUse = VST_ENTRY_7_ABBREV;
1428     }
1429
1430     NameVals.push_back(VE.getValueID(SI->getValue()));
1431     for (const char *P = Name.getKeyData(),
1432          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1433       NameVals.push_back((unsigned char)*P);
1434
1435     // Emit the finished record.
1436     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1437     NameVals.clear();
1438   }
1439   Stream.ExitBlock();
1440 }
1441
1442 /// WriteFunction - Emit a function body to the module stream.
1443 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1444                           BitstreamWriter &Stream) {
1445   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1446   VE.incorporateFunction(F);
1447
1448   SmallVector<unsigned, 64> Vals;
1449
1450   // Emit the number of basic blocks, so the reader can create them ahead of
1451   // time.
1452   Vals.push_back(VE.getBasicBlocks().size());
1453   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1454   Vals.clear();
1455
1456   // If there are function-local constants, emit them now.
1457   unsigned CstStart, CstEnd;
1458   VE.getFunctionConstantRange(CstStart, CstEnd);
1459   WriteConstants(CstStart, CstEnd, VE, Stream, false);
1460
1461   // If there is function-local metadata, emit it now.
1462   WriteFunctionLocalMetadata(F, VE, Stream);
1463
1464   // Keep a running idea of what the instruction ID is.
1465   unsigned InstID = CstEnd;
1466
1467   bool NeedsMetadataAttachment = false;
1468   
1469   DebugLoc LastDL;
1470   
1471   // Finally, emit all the instructions, in order.
1472   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1473     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1474          I != E; ++I) {
1475       WriteInstruction(*I, InstID, VE, Stream, Vals);
1476       
1477       if (!I->getType()->isVoidTy())
1478         ++InstID;
1479       
1480       // If the instruction has metadata, write a metadata attachment later.
1481       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1482       
1483       // If the instruction has a debug location, emit it.
1484       DebugLoc DL = I->getDebugLoc();
1485       if (DL.isUnknown()) {
1486         // nothing todo.
1487       } else if (DL == LastDL) {
1488         // Just repeat the same debug loc as last time.
1489         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1490       } else {
1491         MDNode *Scope, *IA;
1492         DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1493         
1494         Vals.push_back(DL.getLine());
1495         Vals.push_back(DL.getCol());
1496         Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1497         Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1498         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1499         Vals.clear();
1500         
1501         LastDL = DL;
1502       }
1503     }
1504
1505   // Emit names for all the instructions etc.
1506   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1507
1508   if (NeedsMetadataAttachment)
1509     WriteMetadataAttachment(F, VE, Stream);
1510   VE.purgeFunction();
1511   Stream.ExitBlock();
1512 }
1513
1514 // Emit blockinfo, which defines the standard abbreviations etc.
1515 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1516   // We only want to emit block info records for blocks that have multiple
1517   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.  Other
1518   // blocks can defined their abbrevs inline.
1519   Stream.EnterBlockInfoBlock(2);
1520
1521   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1522     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1523     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1524     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1525     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1526     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1527     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1528                                    Abbv) != VST_ENTRY_8_ABBREV)
1529       llvm_unreachable("Unexpected abbrev ordering!");
1530   }
1531
1532   { // 7-bit fixed width VST_ENTRY strings.
1533     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1534     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1535     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1536     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1537     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1538     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1539                                    Abbv) != VST_ENTRY_7_ABBREV)
1540       llvm_unreachable("Unexpected abbrev ordering!");
1541   }
1542   { // 6-bit char6 VST_ENTRY strings.
1543     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1544     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1545     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1546     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1547     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1548     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1549                                    Abbv) != VST_ENTRY_6_ABBREV)
1550       llvm_unreachable("Unexpected abbrev ordering!");
1551   }
1552   { // 6-bit char6 VST_BBENTRY strings.
1553     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1554     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1555     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1556     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1557     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1558     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1559                                    Abbv) != VST_BBENTRY_6_ABBREV)
1560       llvm_unreachable("Unexpected abbrev ordering!");
1561   }
1562
1563
1564
1565   { // SETTYPE abbrev for CONSTANTS_BLOCK.
1566     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1567     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1568     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1569                               Log2_32_Ceil(VE.getTypes().size()+1)));
1570     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1571                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
1572       llvm_unreachable("Unexpected abbrev ordering!");
1573   }
1574
1575   { // INTEGER abbrev for CONSTANTS_BLOCK.
1576     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1577     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1578     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1579     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1580                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
1581       llvm_unreachable("Unexpected abbrev ordering!");
1582   }
1583
1584   { // CE_CAST abbrev for CONSTANTS_BLOCK.
1585     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1586     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1587     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
1588     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
1589                               Log2_32_Ceil(VE.getTypes().size()+1)));
1590     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
1591
1592     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1593                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
1594       llvm_unreachable("Unexpected abbrev ordering!");
1595   }
1596   { // NULL abbrev for CONSTANTS_BLOCK.
1597     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1598     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1599     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1600                                    Abbv) != CONSTANTS_NULL_Abbrev)
1601       llvm_unreachable("Unexpected abbrev ordering!");
1602   }
1603
1604   // FIXME: This should only use space for first class types!
1605
1606   { // INST_LOAD abbrev for FUNCTION_BLOCK.
1607     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1608     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1609     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1610     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1611     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1612     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1613                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
1614       llvm_unreachable("Unexpected abbrev ordering!");
1615   }
1616   { // INST_BINOP abbrev for FUNCTION_BLOCK.
1617     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1618     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1619     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1620     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1621     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1622     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1623                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
1624       llvm_unreachable("Unexpected abbrev ordering!");
1625   }
1626   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1627     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1628     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1629     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1630     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1631     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1632     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1633     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1634                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1635       llvm_unreachable("Unexpected abbrev ordering!");
1636   }
1637   { // INST_CAST abbrev for FUNCTION_BLOCK.
1638     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1639     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1640     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
1641     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
1642                               Log2_32_Ceil(VE.getTypes().size()+1)));
1643     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
1644     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1645                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
1646       llvm_unreachable("Unexpected abbrev ordering!");
1647   }
1648
1649   { // INST_RET abbrev for FUNCTION_BLOCK.
1650     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1651     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1652     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1653                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1654       llvm_unreachable("Unexpected abbrev ordering!");
1655   }
1656   { // INST_RET abbrev for FUNCTION_BLOCK.
1657     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1658     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1659     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1660     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1661                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1662       llvm_unreachable("Unexpected abbrev ordering!");
1663   }
1664   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1665     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1666     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1667     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1668                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1669       llvm_unreachable("Unexpected abbrev ordering!");
1670   }
1671
1672   Stream.ExitBlock();
1673 }
1674
1675 // Sort the Users based on the order in which the reader parses the bitcode 
1676 // file.
1677 static bool bitcodereader_order(const User *lhs, const User *rhs) {
1678   // TODO: Implement.
1679   return true;
1680 }
1681
1682 static void WriteUseList(const Value *V, const ValueEnumerator &VE,
1683                          BitstreamWriter &Stream) {
1684
1685   // One or zero uses can't get out of order.
1686   if (V->use_empty() || V->hasNUses(1))
1687     return;
1688
1689   // Make a copy of the in-memory use-list for sorting.
1690   unsigned UseListSize = std::distance(V->use_begin(), V->use_end());
1691   SmallVector<const User*, 8> UseList;
1692   UseList.reserve(UseListSize);
1693   for (Value::const_use_iterator I = V->use_begin(), E = V->use_end();
1694        I != E; ++I) {
1695     const User *U = *I;
1696     UseList.push_back(U);
1697   }
1698
1699   // Sort the copy based on the order read by the BitcodeReader.
1700   std::sort(UseList.begin(), UseList.end(), bitcodereader_order);
1701
1702   // TODO: Generate a diff between the BitcodeWriter in-memory use-list and the
1703   // sorted list (i.e., the expected BitcodeReader in-memory use-list).
1704
1705   // TODO: Emit the USELIST_CODE_ENTRYs.
1706 }
1707
1708 static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE,
1709                                  BitstreamWriter &Stream) {
1710   VE.incorporateFunction(*F);
1711
1712   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1713        AI != AE; ++AI)
1714     WriteUseList(AI, VE, Stream);
1715   for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE;
1716        ++BB) {
1717     WriteUseList(BB, VE, Stream);
1718     for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
1719          ++II) {
1720       WriteUseList(II, VE, Stream);
1721       for (User::const_op_iterator OI = II->op_begin(), E = II->op_end();
1722            OI != E; ++OI) {
1723         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
1724             isa<InlineAsm>(*OI))
1725           WriteUseList(*OI, VE, Stream);
1726       }
1727     }
1728   }
1729   VE.purgeFunction();
1730 }
1731
1732 // Emit use-lists.
1733 static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE,
1734                                 BitstreamWriter &Stream) {
1735   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
1736
1737   // XXX: this modifies the module, but in a way that should never change the
1738   // behavior of any pass or codegen in LLVM. The problem is that GVs may
1739   // contain entries in the use_list that do not exist in the Module and are
1740   // not stored in the .bc file.
1741   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1742        I != E; ++I)
1743     I->removeDeadConstantUsers();
1744   
1745   // Write the global variables.
1746   for (Module::const_global_iterator GI = M->global_begin(), 
1747          GE = M->global_end(); GI != GE; ++GI) {
1748     WriteUseList(GI, VE, Stream);
1749
1750     // Write the global variable initializers.
1751     if (GI->hasInitializer())
1752       WriteUseList(GI->getInitializer(), VE, Stream);
1753   }
1754
1755   // Write the functions.
1756   for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
1757     WriteUseList(FI, VE, Stream);
1758     if (!FI->isDeclaration())
1759       WriteFunctionUseList(FI, VE, Stream);
1760   }
1761
1762   // Write the aliases.
1763   for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end();
1764        AI != AE; ++AI) {
1765     WriteUseList(AI, VE, Stream);
1766     WriteUseList(AI->getAliasee(), VE, Stream);
1767   }
1768
1769   Stream.ExitBlock();
1770 }
1771
1772 /// WriteModule - Emit the specified module to the bitstream.
1773 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1774   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1775
1776   // Emit the version number if it is non-zero.
1777   if (CurVersion) {
1778     SmallVector<unsigned, 1> Vals;
1779     Vals.push_back(CurVersion);
1780     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1781   }
1782
1783   // Analyze the module, enumerating globals, functions, etc.
1784   ValueEnumerator VE(M);
1785
1786   // Emit blockinfo, which defines the standard abbreviations etc.
1787   WriteBlockInfo(VE, Stream);
1788
1789   // Emit information about parameter attributes.
1790   WriteAttributeTable(VE, Stream);
1791
1792   // Emit information describing all of the types in the module.
1793   WriteTypeTable(VE, Stream);
1794
1795   // Emit top-level description of module, including target triple, inline asm,
1796   // descriptors for global variables, and function prototype info.
1797   WriteModuleInfo(M, VE, Stream);
1798
1799   // Emit constants.
1800   WriteModuleConstants(VE, Stream);
1801
1802   // Emit metadata.
1803   WriteModuleMetadata(M, VE, Stream);
1804
1805   // Emit metadata.
1806   WriteModuleMetadataStore(M, Stream);
1807
1808   // Emit names for globals/functions etc.
1809   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1810
1811   // Emit use-lists.
1812   if (EnablePreserveUseListOrdering)
1813     WriteModuleUseLists(M, VE, Stream);
1814
1815   // Emit function bodies.
1816   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1817     if (!F->isDeclaration())
1818       WriteFunction(*F, VE, Stream);
1819
1820   Stream.ExitBlock();
1821 }
1822
1823 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1824 /// header and trailer to make it compatible with the system archiver.  To do
1825 /// this we emit the following header, and then emit a trailer that pads the
1826 /// file out to be a multiple of 16 bytes.
1827 ///
1828 /// struct bc_header {
1829 ///   uint32_t Magic;         // 0x0B17C0DE
1830 ///   uint32_t Version;       // Version, currently always 0.
1831 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1832 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
1833 ///   uint32_t CPUType;       // CPU specifier.
1834 ///   ... potentially more later ...
1835 /// };
1836 enum {
1837   DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1838   DarwinBCHeaderSize = 5*4
1839 };
1840
1841 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
1842                                uint32_t &Position) {
1843   Buffer[Position + 0] = (unsigned char) (Value >>  0);
1844   Buffer[Position + 1] = (unsigned char) (Value >>  8);
1845   Buffer[Position + 2] = (unsigned char) (Value >> 16);
1846   Buffer[Position + 3] = (unsigned char) (Value >> 24);
1847   Position += 4;
1848 }
1849
1850 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
1851                                          const Triple &TT) {
1852   unsigned CPUType = ~0U;
1853
1854   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1855   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1856   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
1857   // specific constants here because they are implicitly part of the Darwin ABI.
1858   enum {
1859     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
1860     DARWIN_CPU_TYPE_X86        = 7,
1861     DARWIN_CPU_TYPE_ARM        = 12,
1862     DARWIN_CPU_TYPE_POWERPC    = 18
1863   };
1864
1865   Triple::ArchType Arch = TT.getArch();
1866   if (Arch == Triple::x86_64)
1867     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1868   else if (Arch == Triple::x86)
1869     CPUType = DARWIN_CPU_TYPE_X86;
1870   else if (Arch == Triple::ppc)
1871     CPUType = DARWIN_CPU_TYPE_POWERPC;
1872   else if (Arch == Triple::ppc64)
1873     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1874   else if (Arch == Triple::arm || Arch == Triple::thumb)
1875     CPUType = DARWIN_CPU_TYPE_ARM;
1876
1877   // Traditional Bitcode starts after header.
1878   assert(Buffer.size() >= DarwinBCHeaderSize &&
1879          "Expected header size to be reserved");
1880   unsigned BCOffset = DarwinBCHeaderSize;
1881   unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
1882
1883   // Write the magic and version.
1884   unsigned Position = 0;
1885   WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
1886   WriteInt32ToBuffer(0          , Buffer, Position); // Version.
1887   WriteInt32ToBuffer(BCOffset   , Buffer, Position);
1888   WriteInt32ToBuffer(BCSize     , Buffer, Position);
1889   WriteInt32ToBuffer(CPUType    , Buffer, Position);
1890
1891   // If the file is not a multiple of 16 bytes, insert dummy padding.
1892   while (Buffer.size() & 15)
1893     Buffer.push_back(0);
1894 }
1895
1896 /// WriteBitcodeToFile - Write the specified module to the specified output
1897 /// stream.
1898 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1899   SmallVector<char, 1024> Buffer;
1900   Buffer.reserve(256*1024);
1901
1902   // If this is darwin or another generic macho target, reserve space for the
1903   // header.
1904   Triple TT(M->getTargetTriple());
1905   if (TT.isOSDarwin())
1906     Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
1907
1908   // Emit the module into the buffer.
1909   {
1910     BitstreamWriter Stream(Buffer);
1911
1912     // Emit the file header.
1913     Stream.Emit((unsigned)'B', 8);
1914     Stream.Emit((unsigned)'C', 8);
1915     Stream.Emit(0x0, 4);
1916     Stream.Emit(0xC, 4);
1917     Stream.Emit(0xE, 4);
1918     Stream.Emit(0xD, 4);
1919
1920     // Emit the module.
1921     WriteModule(M, Stream);
1922   }
1923
1924   if (TT.isOSDarwin())
1925     EmitDarwinBCHeaderAndTrailer(Buffer, TT);
1926
1927   // Write the generated bitstream to "Out".
1928   Out.write((char*)&Buffer.front(), Buffer.size());
1929 }