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