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