1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Bitcode writer implementation.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "llvm/Bitcode/BitstreamWriter.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "ValueEnumerator.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/InlineAsm.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Operator.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Support/Program.h"
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.
39 // VALUE_SYMTAB_BLOCK abbrev id's.
40 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
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,
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
62 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
64 default: llvm_unreachable("Unknown cast instruction!");
65 case Instruction::Trunc : return bitc::CAST_TRUNC;
66 case Instruction::ZExt : return bitc::CAST_ZEXT;
67 case Instruction::SExt : return bitc::CAST_SEXT;
68 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
69 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
70 case Instruction::UIToFP : return bitc::CAST_UITOFP;
71 case Instruction::SIToFP : return bitc::CAST_SITOFP;
72 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
73 case Instruction::FPExt : return bitc::CAST_FPEXT;
74 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
75 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
76 case Instruction::BitCast : return bitc::CAST_BITCAST;
80 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
82 default: llvm_unreachable("Unknown binary instruction!");
83 case Instruction::Add:
84 case Instruction::FAdd: return bitc::BINOP_ADD;
85 case Instruction::Sub:
86 case Instruction::FSub: return bitc::BINOP_SUB;
87 case Instruction::Mul:
88 case Instruction::FMul: return bitc::BINOP_MUL;
89 case Instruction::UDiv: return bitc::BINOP_UDIV;
90 case Instruction::FDiv:
91 case Instruction::SDiv: return bitc::BINOP_SDIV;
92 case Instruction::URem: return bitc::BINOP_UREM;
93 case Instruction::FRem:
94 case Instruction::SRem: return bitc::BINOP_SREM;
95 case Instruction::Shl: return bitc::BINOP_SHL;
96 case Instruction::LShr: return bitc::BINOP_LSHR;
97 case Instruction::AShr: return bitc::BINOP_ASHR;
98 case Instruction::And: return bitc::BINOP_AND;
99 case Instruction::Or: return bitc::BINOP_OR;
100 case Instruction::Xor: return bitc::BINOP_XOR;
104 static void WriteStringRecord(unsigned Code, const std::string &Str,
105 unsigned AbbrevToUse, BitstreamWriter &Stream) {
106 SmallVector<unsigned, 64> Vals;
108 // Code: [strchar x N]
109 for (unsigned i = 0, e = Str.size(); i != e; ++i)
110 Vals.push_back(Str[i]);
112 // Emit the finished record.
113 Stream.EmitRecord(Code, Vals, AbbrevToUse);
116 // Emit information about parameter attributes.
117 static void WriteAttributeTable(const ValueEnumerator &VE,
118 BitstreamWriter &Stream) {
119 const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
120 if (Attrs.empty()) return;
122 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
124 SmallVector<uint64_t, 64> Record;
125 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
126 const AttrListPtr &A = Attrs[i];
127 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
128 const AttributeWithIndex &PAWI = A.getSlot(i);
129 Record.push_back(PAWI.Index);
131 // FIXME: remove in LLVM 3.0
132 // Store the alignment in the bitcode as a 16-bit raw value instead of a
133 // 5-bit log2 encoded value. Shift the bits above the alignment up by
135 uint64_t FauxAttr = PAWI.Attrs & 0xffff;
136 if (PAWI.Attrs & Attribute::Alignment)
137 FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
138 FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
140 Record.push_back(FauxAttr);
143 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
150 /// WriteTypeTable - Write out the type table for a module.
151 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
152 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
154 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
155 SmallVector<uint64_t, 64> TypeVals;
157 // Abbrev for TYPE_CODE_POINTER.
158 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
159 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
161 Log2_32_Ceil(VE.getTypes().size()+1)));
162 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
163 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
165 // Abbrev for TYPE_CODE_FUNCTION.
166 Abbv = new BitCodeAbbrev();
167 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
168 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
169 Abbv->Add(BitCodeAbbrevOp(0)); // FIXME: DEAD value, remove in LLVM 3.0
170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
172 Log2_32_Ceil(VE.getTypes().size()+1)));
173 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
175 // Abbrev for TYPE_CODE_STRUCT.
176 Abbv = new BitCodeAbbrev();
177 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
178 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
179 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
181 Log2_32_Ceil(VE.getTypes().size()+1)));
182 unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
184 // Abbrev for TYPE_CODE_ARRAY.
185 Abbv = new BitCodeAbbrev();
186 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
189 Log2_32_Ceil(VE.getTypes().size()+1)));
190 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
192 // Emit an entry count so the reader can reserve space.
193 TypeVals.push_back(TypeList.size());
194 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
197 // Loop over all of the types, emitting each in turn.
198 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
199 const Type *T = TypeList[i];
203 switch (T->getTypeID()) {
204 default: llvm_unreachable("Unknown type!");
205 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
206 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
207 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
208 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
209 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
210 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
211 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
212 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
213 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
214 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
215 case Type::IntegerTyID:
217 Code = bitc::TYPE_CODE_INTEGER;
218 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
220 case Type::PointerTyID: {
221 const PointerType *PTy = cast<PointerType>(T);
222 // POINTER: [pointee type, address space]
223 Code = bitc::TYPE_CODE_POINTER;
224 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
225 unsigned AddressSpace = PTy->getAddressSpace();
226 TypeVals.push_back(AddressSpace);
227 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
230 case Type::FunctionTyID: {
231 const FunctionType *FT = cast<FunctionType>(T);
232 // FUNCTION: [isvararg, attrid, retty, paramty x N]
233 Code = bitc::TYPE_CODE_FUNCTION;
234 TypeVals.push_back(FT->isVarArg());
235 TypeVals.push_back(0); // FIXME: DEAD: remove in llvm 3.0
236 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
237 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
238 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
239 AbbrevToUse = FunctionAbbrev;
242 case Type::StructTyID: {
243 const StructType *ST = cast<StructType>(T);
244 // STRUCT: [ispacked, eltty x N]
245 Code = bitc::TYPE_CODE_STRUCT;
246 TypeVals.push_back(ST->isPacked());
247 // Output all of the element types.
248 for (StructType::element_iterator I = ST->element_begin(),
249 E = ST->element_end(); I != E; ++I)
250 TypeVals.push_back(VE.getTypeID(*I));
251 AbbrevToUse = StructAbbrev;
254 case Type::ArrayTyID: {
255 const ArrayType *AT = cast<ArrayType>(T);
256 // ARRAY: [numelts, eltty]
257 Code = bitc::TYPE_CODE_ARRAY;
258 TypeVals.push_back(AT->getNumElements());
259 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
260 AbbrevToUse = ArrayAbbrev;
263 case Type::VectorTyID: {
264 const VectorType *VT = cast<VectorType>(T);
265 // VECTOR [numelts, eltty]
266 Code = bitc::TYPE_CODE_VECTOR;
267 TypeVals.push_back(VT->getNumElements());
268 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
273 // Emit the finished record.
274 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
281 static unsigned getEncodedLinkage(const GlobalValue *GV) {
282 switch (GV->getLinkage()) {
283 default: llvm_unreachable("Invalid linkage!");
284 case GlobalValue::ExternalLinkage: return 0;
285 case GlobalValue::WeakAnyLinkage: return 1;
286 case GlobalValue::AppendingLinkage: return 2;
287 case GlobalValue::InternalLinkage: return 3;
288 case GlobalValue::LinkOnceAnyLinkage: return 4;
289 case GlobalValue::DLLImportLinkage: return 5;
290 case GlobalValue::DLLExportLinkage: return 6;
291 case GlobalValue::ExternalWeakLinkage: return 7;
292 case GlobalValue::CommonLinkage: return 8;
293 case GlobalValue::PrivateLinkage: return 9;
294 case GlobalValue::WeakODRLinkage: return 10;
295 case GlobalValue::LinkOnceODRLinkage: return 11;
296 case GlobalValue::AvailableExternallyLinkage: return 12;
297 case GlobalValue::LinkerPrivateLinkage: return 13;
298 case GlobalValue::LinkerPrivateWeakLinkage: return 14;
299 case GlobalValue::LinkerPrivateWeakDefAutoLinkage: return 15;
303 static unsigned getEncodedVisibility(const GlobalValue *GV) {
304 switch (GV->getVisibility()) {
305 default: llvm_unreachable("Invalid visibility!");
306 case GlobalValue::DefaultVisibility: return 0;
307 case GlobalValue::HiddenVisibility: return 1;
308 case GlobalValue::ProtectedVisibility: return 2;
312 // Emit top-level description of module, including target triple, inline asm,
313 // descriptors for global variables, and function prototype info.
314 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
315 BitstreamWriter &Stream) {
316 // Emit the list of dependent libraries for the Module.
317 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
318 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
320 // Emit various pieces of data attached to a module.
321 if (!M->getTargetTriple().empty())
322 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
324 if (!M->getDataLayout().empty())
325 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
327 if (!M->getModuleInlineAsm().empty())
328 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
331 // Emit information about sections and GC, computing how many there are. Also
332 // compute the maximum alignment value.
333 std::map<std::string, unsigned> SectionMap;
334 std::map<std::string, unsigned> GCMap;
335 unsigned MaxAlignment = 0;
336 unsigned MaxGlobalType = 0;
337 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
339 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
340 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
342 if (!GV->hasSection()) continue;
343 // Give section names unique ID's.
344 unsigned &Entry = SectionMap[GV->getSection()];
345 if (Entry != 0) continue;
346 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
348 Entry = SectionMap.size();
350 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
351 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
352 if (F->hasSection()) {
353 // Give section names unique ID's.
354 unsigned &Entry = SectionMap[F->getSection()];
356 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
358 Entry = SectionMap.size();
362 // Same for GC names.
363 unsigned &Entry = GCMap[F->getGC()];
365 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
367 Entry = GCMap.size();
372 // Emit abbrev for globals, now that we know # sections and max alignment.
373 unsigned SimpleGVarAbbrev = 0;
374 if (!M->global_empty()) {
375 // Add an abbrev for common globals with no visibility or thread localness.
376 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
377 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
378 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
379 Log2_32_Ceil(MaxGlobalType+1)));
380 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
381 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
382 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
383 if (MaxAlignment == 0) // Alignment.
384 Abbv->Add(BitCodeAbbrevOp(0));
386 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
387 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
388 Log2_32_Ceil(MaxEncAlignment+1)));
390 if (SectionMap.empty()) // Section.
391 Abbv->Add(BitCodeAbbrevOp(0));
393 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
394 Log2_32_Ceil(SectionMap.size()+1)));
395 // Don't bother emitting vis + thread local.
396 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
399 // Emit the global variable information.
400 SmallVector<unsigned, 64> Vals;
401 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
403 unsigned AbbrevToUse = 0;
405 // GLOBALVAR: [type, isconst, initid,
406 // linkage, alignment, section, visibility, threadlocal,
408 Vals.push_back(VE.getTypeID(GV->getType()));
409 Vals.push_back(GV->isConstant());
410 Vals.push_back(GV->isDeclaration() ? 0 :
411 (VE.getValueID(GV->getInitializer()) + 1));
412 Vals.push_back(getEncodedLinkage(GV));
413 Vals.push_back(Log2_32(GV->getAlignment())+1);
414 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
415 if (GV->isThreadLocal() ||
416 GV->getVisibility() != GlobalValue::DefaultVisibility ||
417 GV->hasUnnamedAddr()) {
418 Vals.push_back(getEncodedVisibility(GV));
419 Vals.push_back(GV->isThreadLocal());
420 Vals.push_back(GV->hasUnnamedAddr());
422 AbbrevToUse = SimpleGVarAbbrev;
425 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
429 // Emit the function proto information.
430 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
431 // FUNCTION: [type, callingconv, isproto, paramattr,
432 // linkage, alignment, section, visibility, gc, unnamed_addr]
433 Vals.push_back(VE.getTypeID(F->getType()));
434 Vals.push_back(F->getCallingConv());
435 Vals.push_back(F->isDeclaration());
436 Vals.push_back(getEncodedLinkage(F));
437 Vals.push_back(VE.getAttributeID(F->getAttributes()));
438 Vals.push_back(Log2_32(F->getAlignment())+1);
439 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
440 Vals.push_back(getEncodedVisibility(F));
441 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
442 Vals.push_back(F->hasUnnamedAddr());
444 unsigned AbbrevToUse = 0;
445 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
449 // Emit the alias information.
450 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
452 Vals.push_back(VE.getTypeID(AI->getType()));
453 Vals.push_back(VE.getValueID(AI->getAliasee()));
454 Vals.push_back(getEncodedLinkage(AI));
455 Vals.push_back(getEncodedVisibility(AI));
456 unsigned AbbrevToUse = 0;
457 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
462 static uint64_t GetOptimizationFlags(const Value *V) {
465 if (const OverflowingBinaryOperator *OBO =
466 dyn_cast<OverflowingBinaryOperator>(V)) {
467 if (OBO->hasNoSignedWrap())
468 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
469 if (OBO->hasNoUnsignedWrap())
470 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
471 } else if (const PossiblyExactOperator *PEO =
472 dyn_cast<PossiblyExactOperator>(V)) {
474 Flags |= 1 << bitc::PEO_EXACT;
480 static void WriteMDNode(const MDNode *N,
481 const ValueEnumerator &VE,
482 BitstreamWriter &Stream,
483 SmallVector<uint64_t, 64> &Record) {
484 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
485 if (N->getOperand(i)) {
486 Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
487 Record.push_back(VE.getValueID(N->getOperand(i)));
489 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
493 unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
495 Stream.EmitRecord(MDCode, Record, 0);
499 static void WriteModuleMetadata(const Module *M,
500 const ValueEnumerator &VE,
501 BitstreamWriter &Stream) {
502 const ValueEnumerator::ValueList &Vals = VE.getMDValues();
503 bool StartedMetadataBlock = false;
504 unsigned MDSAbbrev = 0;
505 SmallVector<uint64_t, 64> Record;
506 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
508 if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
509 if (!N->isFunctionLocal() || !N->getFunction()) {
510 if (!StartedMetadataBlock) {
511 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
512 StartedMetadataBlock = true;
514 WriteMDNode(N, VE, Stream, Record);
516 } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
517 if (!StartedMetadataBlock) {
518 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
520 // Abbrev for METADATA_STRING.
521 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
522 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
523 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
524 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
525 MDSAbbrev = Stream.EmitAbbrev(Abbv);
526 StartedMetadataBlock = true;
529 // Code: [strchar x N]
530 Record.append(MDS->begin(), MDS->end());
532 // Emit the finished record.
533 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
538 // Write named metadata.
539 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
540 E = M->named_metadata_end(); I != E; ++I) {
541 const NamedMDNode *NMD = I;
542 if (!StartedMetadataBlock) {
543 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
544 StartedMetadataBlock = true;
548 StringRef Str = NMD->getName();
549 for (unsigned i = 0, e = Str.size(); i != e; ++i)
550 Record.push_back(Str[i]);
551 Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
554 // Write named metadata operands.
555 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
556 Record.push_back(VE.getValueID(NMD->getOperand(i)));
557 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
561 if (StartedMetadataBlock)
565 static void WriteFunctionLocalMetadata(const Function &F,
566 const ValueEnumerator &VE,
567 BitstreamWriter &Stream) {
568 bool StartedMetadataBlock = false;
569 SmallVector<uint64_t, 64> Record;
570 const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues();
571 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
572 if (const MDNode *N = Vals[i])
573 if (N->isFunctionLocal() && N->getFunction() == &F) {
574 if (!StartedMetadataBlock) {
575 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
576 StartedMetadataBlock = true;
578 WriteMDNode(N, VE, Stream, Record);
581 if (StartedMetadataBlock)
585 static void WriteMetadataAttachment(const Function &F,
586 const ValueEnumerator &VE,
587 BitstreamWriter &Stream) {
588 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
590 SmallVector<uint64_t, 64> Record;
592 // Write metadata attachments
593 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
594 SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
596 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
597 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
600 I->getAllMetadataOtherThanDebugLoc(MDs);
602 // If no metadata, ignore instruction.
603 if (MDs.empty()) continue;
605 Record.push_back(VE.getInstructionID(I));
607 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
608 Record.push_back(MDs[i].first);
609 Record.push_back(VE.getValueID(MDs[i].second));
611 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
618 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
619 SmallVector<uint64_t, 64> Record;
621 // Write metadata kinds
622 // METADATA_KIND - [n x [id, name]]
623 SmallVector<StringRef, 4> Names;
624 M->getMDKindNames(Names);
626 if (Names.empty()) return;
628 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
630 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
631 Record.push_back(MDKindID);
632 StringRef KName = Names[MDKindID];
633 Record.append(KName.begin(), KName.end());
635 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
642 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
643 const ValueEnumerator &VE,
644 BitstreamWriter &Stream, bool isGlobal) {
645 if (FirstVal == LastVal) return;
647 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
649 unsigned AggregateAbbrev = 0;
650 unsigned String8Abbrev = 0;
651 unsigned CString7Abbrev = 0;
652 unsigned CString6Abbrev = 0;
653 // If this is a constant pool for the module, emit module-specific abbrevs.
655 // Abbrev for CST_CODE_AGGREGATE.
656 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
657 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
658 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
659 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
660 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
662 // Abbrev for CST_CODE_STRING.
663 Abbv = new BitCodeAbbrev();
664 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
665 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
666 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
667 String8Abbrev = Stream.EmitAbbrev(Abbv);
668 // Abbrev for CST_CODE_CSTRING.
669 Abbv = new BitCodeAbbrev();
670 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
671 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
672 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
673 CString7Abbrev = Stream.EmitAbbrev(Abbv);
674 // Abbrev for CST_CODE_CSTRING.
675 Abbv = new BitCodeAbbrev();
676 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
677 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
678 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
679 CString6Abbrev = Stream.EmitAbbrev(Abbv);
682 SmallVector<uint64_t, 64> Record;
684 const ValueEnumerator::ValueList &Vals = VE.getValues();
685 const Type *LastTy = 0;
686 for (unsigned i = FirstVal; i != LastVal; ++i) {
687 const Value *V = Vals[i].first;
688 // If we need to switch types, do so now.
689 if (V->getType() != LastTy) {
690 LastTy = V->getType();
691 Record.push_back(VE.getTypeID(LastTy));
692 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
693 CONSTANTS_SETTYPE_ABBREV);
697 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
698 Record.push_back(unsigned(IA->hasSideEffects()) |
699 unsigned(IA->isAlignStack()) << 1);
701 // Add the asm string.
702 const std::string &AsmStr = IA->getAsmString();
703 Record.push_back(AsmStr.size());
704 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
705 Record.push_back(AsmStr[i]);
707 // Add the constraint string.
708 const std::string &ConstraintStr = IA->getConstraintString();
709 Record.push_back(ConstraintStr.size());
710 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
711 Record.push_back(ConstraintStr[i]);
712 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
716 const Constant *C = cast<Constant>(V);
718 unsigned AbbrevToUse = 0;
719 if (C->isNullValue()) {
720 Code = bitc::CST_CODE_NULL;
721 } else if (isa<UndefValue>(C)) {
722 Code = bitc::CST_CODE_UNDEF;
723 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
724 if (IV->getBitWidth() <= 64) {
725 uint64_t V = IV->getSExtValue();
727 Record.push_back(V << 1);
729 Record.push_back((-V << 1) | 1);
730 Code = bitc::CST_CODE_INTEGER;
731 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
732 } else { // Wide integers, > 64 bits in size.
733 // We have an arbitrary precision integer value to write whose
734 // bit width is > 64. However, in canonical unsigned integer
735 // format it is likely that the high bits are going to be zero.
736 // So, we only write the number of active words.
737 unsigned NWords = IV->getValue().getActiveWords();
738 const uint64_t *RawWords = IV->getValue().getRawData();
739 for (unsigned i = 0; i != NWords; ++i) {
740 int64_t V = RawWords[i];
742 Record.push_back(V << 1);
744 Record.push_back((-V << 1) | 1);
746 Code = bitc::CST_CODE_WIDE_INTEGER;
748 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
749 Code = bitc::CST_CODE_FLOAT;
750 const Type *Ty = CFP->getType();
751 if (Ty->isFloatTy() || Ty->isDoubleTy()) {
752 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
753 } else if (Ty->isX86_FP80Ty()) {
754 // api needed to prevent premature destruction
755 // bits are not in the same order as a normal i80 APInt, compensate.
756 APInt api = CFP->getValueAPF().bitcastToAPInt();
757 const uint64_t *p = api.getRawData();
758 Record.push_back((p[1] << 48) | (p[0] >> 16));
759 Record.push_back(p[0] & 0xffffLL);
760 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
761 APInt api = CFP->getValueAPF().bitcastToAPInt();
762 const uint64_t *p = api.getRawData();
763 Record.push_back(p[0]);
764 Record.push_back(p[1]);
766 assert (0 && "Unknown FP type!");
768 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
769 const ConstantArray *CA = cast<ConstantArray>(C);
770 // Emit constant strings specially.
771 unsigned NumOps = CA->getNumOperands();
772 // If this is a null-terminated string, use the denser CSTRING encoding.
773 if (CA->getOperand(NumOps-1)->isNullValue()) {
774 Code = bitc::CST_CODE_CSTRING;
775 --NumOps; // Don't encode the null, which isn't allowed by char6.
777 Code = bitc::CST_CODE_STRING;
778 AbbrevToUse = String8Abbrev;
780 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
781 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
782 for (unsigned i = 0; i != NumOps; ++i) {
783 unsigned char V = cast<ConstantInt>(CA->getOperand(i))->getZExtValue();
785 isCStr7 &= (V & 128) == 0;
787 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
791 AbbrevToUse = CString6Abbrev;
793 AbbrevToUse = CString7Abbrev;
794 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
795 isa<ConstantVector>(V)) {
796 Code = bitc::CST_CODE_AGGREGATE;
797 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
798 Record.push_back(VE.getValueID(C->getOperand(i)));
799 AbbrevToUse = AggregateAbbrev;
800 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
801 switch (CE->getOpcode()) {
803 if (Instruction::isCast(CE->getOpcode())) {
804 Code = bitc::CST_CODE_CE_CAST;
805 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
806 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
807 Record.push_back(VE.getValueID(C->getOperand(0)));
808 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
810 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
811 Code = bitc::CST_CODE_CE_BINOP;
812 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
813 Record.push_back(VE.getValueID(C->getOperand(0)));
814 Record.push_back(VE.getValueID(C->getOperand(1)));
815 uint64_t Flags = GetOptimizationFlags(CE);
817 Record.push_back(Flags);
820 case Instruction::GetElementPtr:
821 Code = bitc::CST_CODE_CE_GEP;
822 if (cast<GEPOperator>(C)->isInBounds())
823 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
824 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
825 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
826 Record.push_back(VE.getValueID(C->getOperand(i)));
829 case Instruction::Select:
830 Code = bitc::CST_CODE_CE_SELECT;
831 Record.push_back(VE.getValueID(C->getOperand(0)));
832 Record.push_back(VE.getValueID(C->getOperand(1)));
833 Record.push_back(VE.getValueID(C->getOperand(2)));
835 case Instruction::ExtractElement:
836 Code = bitc::CST_CODE_CE_EXTRACTELT;
837 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
838 Record.push_back(VE.getValueID(C->getOperand(0)));
839 Record.push_back(VE.getValueID(C->getOperand(1)));
841 case Instruction::InsertElement:
842 Code = bitc::CST_CODE_CE_INSERTELT;
843 Record.push_back(VE.getValueID(C->getOperand(0)));
844 Record.push_back(VE.getValueID(C->getOperand(1)));
845 Record.push_back(VE.getValueID(C->getOperand(2)));
847 case Instruction::ShuffleVector:
848 // If the return type and argument types are the same, this is a
849 // standard shufflevector instruction. If the types are different,
850 // then the shuffle is widening or truncating the input vectors, and
851 // the argument type must also be encoded.
852 if (C->getType() == C->getOperand(0)->getType()) {
853 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
855 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
856 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
858 Record.push_back(VE.getValueID(C->getOperand(0)));
859 Record.push_back(VE.getValueID(C->getOperand(1)));
860 Record.push_back(VE.getValueID(C->getOperand(2)));
862 case Instruction::ICmp:
863 case Instruction::FCmp:
864 Code = bitc::CST_CODE_CE_CMP;
865 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
866 Record.push_back(VE.getValueID(C->getOperand(0)));
867 Record.push_back(VE.getValueID(C->getOperand(1)));
868 Record.push_back(CE->getPredicate());
871 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
872 Code = bitc::CST_CODE_BLOCKADDRESS;
873 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
874 Record.push_back(VE.getValueID(BA->getFunction()));
875 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
880 llvm_unreachable("Unknown constant!");
882 Stream.EmitRecord(Code, Record, AbbrevToUse);
889 static void WriteModuleConstants(const ValueEnumerator &VE,
890 BitstreamWriter &Stream) {
891 const ValueEnumerator::ValueList &Vals = VE.getValues();
893 // Find the first constant to emit, which is the first non-globalvalue value.
894 // We know globalvalues have been emitted by WriteModuleInfo.
895 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
896 if (!isa<GlobalValue>(Vals[i].first)) {
897 WriteConstants(i, Vals.size(), VE, Stream, true);
903 /// PushValueAndType - The file has to encode both the value and type id for
904 /// many values, because we need to know what type to create for forward
905 /// references. However, most operands are not forward references, so this type
906 /// field is not needed.
908 /// This function adds V's value ID to Vals. If the value ID is higher than the
909 /// instruction ID, then it is a forward reference, and it also includes the
911 static bool PushValueAndType(const Value *V, unsigned InstID,
912 SmallVector<unsigned, 64> &Vals,
913 ValueEnumerator &VE) {
914 unsigned ValID = VE.getValueID(V);
915 Vals.push_back(ValID);
916 if (ValID >= InstID) {
917 Vals.push_back(VE.getTypeID(V->getType()));
923 /// WriteInstruction - Emit an instruction to the specified stream.
924 static void WriteInstruction(const Instruction &I, unsigned InstID,
925 ValueEnumerator &VE, BitstreamWriter &Stream,
926 SmallVector<unsigned, 64> &Vals) {
928 unsigned AbbrevToUse = 0;
929 VE.setInstructionID(&I);
930 switch (I.getOpcode()) {
932 if (Instruction::isCast(I.getOpcode())) {
933 Code = bitc::FUNC_CODE_INST_CAST;
934 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
935 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
936 Vals.push_back(VE.getTypeID(I.getType()));
937 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
939 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
940 Code = bitc::FUNC_CODE_INST_BINOP;
941 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
942 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
943 Vals.push_back(VE.getValueID(I.getOperand(1)));
944 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
945 uint64_t Flags = GetOptimizationFlags(&I);
947 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
948 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
949 Vals.push_back(Flags);
954 case Instruction::GetElementPtr:
955 Code = bitc::FUNC_CODE_INST_GEP;
956 if (cast<GEPOperator>(&I)->isInBounds())
957 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
958 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
959 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
961 case Instruction::ExtractValue: {
962 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
963 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
964 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
965 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
969 case Instruction::InsertValue: {
970 Code = bitc::FUNC_CODE_INST_INSERTVAL;
971 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
972 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
973 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
974 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
978 case Instruction::Select:
979 Code = bitc::FUNC_CODE_INST_VSELECT;
980 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
981 Vals.push_back(VE.getValueID(I.getOperand(2)));
982 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
984 case Instruction::ExtractElement:
985 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
986 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
987 Vals.push_back(VE.getValueID(I.getOperand(1)));
989 case Instruction::InsertElement:
990 Code = bitc::FUNC_CODE_INST_INSERTELT;
991 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
992 Vals.push_back(VE.getValueID(I.getOperand(1)));
993 Vals.push_back(VE.getValueID(I.getOperand(2)));
995 case Instruction::ShuffleVector:
996 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
997 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
998 Vals.push_back(VE.getValueID(I.getOperand(1)));
999 Vals.push_back(VE.getValueID(I.getOperand(2)));
1001 case Instruction::ICmp:
1002 case Instruction::FCmp:
1003 // compare returning Int1Ty or vector of Int1Ty
1004 Code = bitc::FUNC_CODE_INST_CMP2;
1005 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1006 Vals.push_back(VE.getValueID(I.getOperand(1)));
1007 Vals.push_back(cast<CmpInst>(I).getPredicate());
1010 case Instruction::Ret:
1012 Code = bitc::FUNC_CODE_INST_RET;
1013 unsigned NumOperands = I.getNumOperands();
1014 if (NumOperands == 0)
1015 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1016 else if (NumOperands == 1) {
1017 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1018 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1020 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1021 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1025 case Instruction::Br:
1027 Code = bitc::FUNC_CODE_INST_BR;
1028 BranchInst &II = cast<BranchInst>(I);
1029 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1030 if (II.isConditional()) {
1031 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1032 Vals.push_back(VE.getValueID(II.getCondition()));
1036 case Instruction::Switch:
1037 Code = bitc::FUNC_CODE_INST_SWITCH;
1038 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1039 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1040 Vals.push_back(VE.getValueID(I.getOperand(i)));
1042 case Instruction::IndirectBr:
1043 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1044 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1045 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1046 Vals.push_back(VE.getValueID(I.getOperand(i)));
1049 case Instruction::Invoke: {
1050 const InvokeInst *II = cast<InvokeInst>(&I);
1051 const Value *Callee(II->getCalledValue());
1052 const PointerType *PTy = cast<PointerType>(Callee->getType());
1053 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1054 Code = bitc::FUNC_CODE_INST_INVOKE;
1056 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1057 Vals.push_back(II->getCallingConv());
1058 Vals.push_back(VE.getValueID(II->getNormalDest()));
1059 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1060 PushValueAndType(Callee, InstID, Vals, VE);
1062 // Emit value #'s for the fixed parameters.
1063 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1064 Vals.push_back(VE.getValueID(I.getOperand(i))); // fixed param.
1066 // Emit type/value pairs for varargs params.
1067 if (FTy->isVarArg()) {
1068 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1070 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1074 case Instruction::Unwind:
1075 Code = bitc::FUNC_CODE_INST_UNWIND;
1077 case Instruction::Unreachable:
1078 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1079 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1082 case Instruction::PHI:
1083 Code = bitc::FUNC_CODE_INST_PHI;
1084 Vals.push_back(VE.getTypeID(I.getType()));
1085 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1086 Vals.push_back(VE.getValueID(I.getOperand(i)));
1089 case Instruction::Alloca:
1090 Code = bitc::FUNC_CODE_INST_ALLOCA;
1091 Vals.push_back(VE.getTypeID(I.getType()));
1092 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1093 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1094 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1097 case Instruction::Load:
1098 Code = bitc::FUNC_CODE_INST_LOAD;
1099 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1100 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1102 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1103 Vals.push_back(cast<LoadInst>(I).isVolatile());
1105 case Instruction::Store:
1106 Code = bitc::FUNC_CODE_INST_STORE;
1107 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1108 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
1109 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1110 Vals.push_back(cast<StoreInst>(I).isVolatile());
1112 case Instruction::Call: {
1113 const CallInst &CI = cast<CallInst>(I);
1114 const PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1115 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1117 Code = bitc::FUNC_CODE_INST_CALL;
1119 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1120 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1121 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1123 // Emit value #'s for the fixed parameters.
1124 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1125 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); // fixed param.
1127 // Emit type/value pairs for varargs params.
1128 if (FTy->isVarArg()) {
1129 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1131 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1135 case Instruction::VAArg:
1136 Code = bitc::FUNC_CODE_INST_VAARG;
1137 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1138 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
1139 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1143 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1147 // Emit names for globals/functions etc.
1148 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1149 const ValueEnumerator &VE,
1150 BitstreamWriter &Stream) {
1151 if (VST.empty()) return;
1152 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1154 // FIXME: Set up the abbrev, we know how many values there are!
1155 // FIXME: We know if the type names can use 7-bit ascii.
1156 SmallVector<unsigned, 64> NameVals;
1158 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1161 const ValueName &Name = *SI;
1163 // Figure out the encoding to use for the name.
1165 bool isChar6 = true;
1166 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1169 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1170 if ((unsigned char)*C & 128) {
1172 break; // don't bother scanning the rest.
1176 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1178 // VST_ENTRY: [valueid, namechar x N]
1179 // VST_BBENTRY: [bbid, namechar x N]
1181 if (isa<BasicBlock>(SI->getValue())) {
1182 Code = bitc::VST_CODE_BBENTRY;
1184 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1186 Code = bitc::VST_CODE_ENTRY;
1188 AbbrevToUse = VST_ENTRY_6_ABBREV;
1190 AbbrevToUse = VST_ENTRY_7_ABBREV;
1193 NameVals.push_back(VE.getValueID(SI->getValue()));
1194 for (const char *P = Name.getKeyData(),
1195 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1196 NameVals.push_back((unsigned char)*P);
1198 // Emit the finished record.
1199 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1205 /// WriteFunction - Emit a function body to the module stream.
1206 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1207 BitstreamWriter &Stream) {
1208 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1209 VE.incorporateFunction(F);
1211 SmallVector<unsigned, 64> Vals;
1213 // Emit the number of basic blocks, so the reader can create them ahead of
1215 Vals.push_back(VE.getBasicBlocks().size());
1216 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1219 // If there are function-local constants, emit them now.
1220 unsigned CstStart, CstEnd;
1221 VE.getFunctionConstantRange(CstStart, CstEnd);
1222 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1224 // If there is function-local metadata, emit it now.
1225 WriteFunctionLocalMetadata(F, VE, Stream);
1227 // Keep a running idea of what the instruction ID is.
1228 unsigned InstID = CstEnd;
1230 bool NeedsMetadataAttachment = false;
1234 // Finally, emit all the instructions, in order.
1235 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1236 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1238 WriteInstruction(*I, InstID, VE, Stream, Vals);
1240 if (!I->getType()->isVoidTy())
1243 // If the instruction has metadata, write a metadata attachment later.
1244 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1246 // If the instruction has a debug location, emit it.
1247 DebugLoc DL = I->getDebugLoc();
1248 if (DL.isUnknown()) {
1250 } else if (DL == LastDL) {
1251 // Just repeat the same debug loc as last time.
1252 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1255 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1257 Vals.push_back(DL.getLine());
1258 Vals.push_back(DL.getCol());
1259 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1260 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1261 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1268 // Emit names for all the instructions etc.
1269 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1271 if (NeedsMetadataAttachment)
1272 WriteMetadataAttachment(F, VE, Stream);
1277 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
1278 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
1279 const ValueEnumerator &VE,
1280 BitstreamWriter &Stream) {
1281 if (TST.empty()) return;
1283 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
1285 // 7-bit fixed width VST_CODE_ENTRY strings.
1286 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1287 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1288 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1289 Log2_32_Ceil(VE.getTypes().size()+1)));
1290 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1291 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1292 unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
1294 SmallVector<unsigned, 64> NameVals;
1296 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1298 // TST_ENTRY: [typeid, namechar x N]
1299 NameVals.push_back(VE.getTypeID(TI->second));
1301 const std::string &Str = TI->first;
1303 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1304 NameVals.push_back((unsigned char)Str[i]);
1309 // Emit the finished record.
1310 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
1317 // Emit blockinfo, which defines the standard abbreviations etc.
1318 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1319 // We only want to emit block info records for blocks that have multiple
1320 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
1321 // blocks can defined their abbrevs inline.
1322 Stream.EnterBlockInfoBlock(2);
1324 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1325 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1326 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1327 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1328 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1329 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1330 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1331 Abbv) != VST_ENTRY_8_ABBREV)
1332 llvm_unreachable("Unexpected abbrev ordering!");
1335 { // 7-bit fixed width VST_ENTRY strings.
1336 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1337 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1338 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1341 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1342 Abbv) != VST_ENTRY_7_ABBREV)
1343 llvm_unreachable("Unexpected abbrev ordering!");
1345 { // 6-bit char6 VST_ENTRY strings.
1346 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1347 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1348 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1349 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1351 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1352 Abbv) != VST_ENTRY_6_ABBREV)
1353 llvm_unreachable("Unexpected abbrev ordering!");
1355 { // 6-bit char6 VST_BBENTRY strings.
1356 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1357 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1358 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1359 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1360 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1361 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1362 Abbv) != VST_BBENTRY_6_ABBREV)
1363 llvm_unreachable("Unexpected abbrev ordering!");
1368 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1369 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1370 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1371 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1372 Log2_32_Ceil(VE.getTypes().size()+1)));
1373 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1374 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1375 llvm_unreachable("Unexpected abbrev ordering!");
1378 { // INTEGER abbrev for CONSTANTS_BLOCK.
1379 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1380 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1381 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1382 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1383 Abbv) != CONSTANTS_INTEGER_ABBREV)
1384 llvm_unreachable("Unexpected abbrev ordering!");
1387 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1388 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1389 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1390 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1391 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1392 Log2_32_Ceil(VE.getTypes().size()+1)));
1393 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1395 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1396 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1397 llvm_unreachable("Unexpected abbrev ordering!");
1399 { // NULL abbrev for CONSTANTS_BLOCK.
1400 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1401 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1402 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1403 Abbv) != CONSTANTS_NULL_Abbrev)
1404 llvm_unreachable("Unexpected abbrev ordering!");
1407 // FIXME: This should only use space for first class types!
1409 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1410 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1411 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1412 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1413 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1414 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1415 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1416 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1417 llvm_unreachable("Unexpected abbrev ordering!");
1419 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1420 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1421 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1422 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1423 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1424 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1425 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1426 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1427 llvm_unreachable("Unexpected abbrev ordering!");
1429 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1430 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1431 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1432 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1433 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1434 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1435 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1436 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1437 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1438 llvm_unreachable("Unexpected abbrev ordering!");
1440 { // INST_CAST abbrev for FUNCTION_BLOCK.
1441 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1442 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1443 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1444 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1445 Log2_32_Ceil(VE.getTypes().size()+1)));
1446 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1447 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1448 Abbv) != FUNCTION_INST_CAST_ABBREV)
1449 llvm_unreachable("Unexpected abbrev ordering!");
1452 { // INST_RET abbrev for FUNCTION_BLOCK.
1453 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1454 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1455 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1456 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1457 llvm_unreachable("Unexpected abbrev ordering!");
1459 { // INST_RET abbrev for FUNCTION_BLOCK.
1460 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1461 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1462 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1463 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1464 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1465 llvm_unreachable("Unexpected abbrev ordering!");
1467 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1468 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1469 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1470 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1471 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1472 llvm_unreachable("Unexpected abbrev ordering!");
1479 /// WriteModule - Emit the specified module to the bitstream.
1480 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1481 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1483 // Emit the version number if it is non-zero.
1485 SmallVector<unsigned, 1> Vals;
1486 Vals.push_back(CurVersion);
1487 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1490 // Analyze the module, enumerating globals, functions, etc.
1491 ValueEnumerator VE(M);
1493 // Emit blockinfo, which defines the standard abbreviations etc.
1494 WriteBlockInfo(VE, Stream);
1496 // Emit information about parameter attributes.
1497 WriteAttributeTable(VE, Stream);
1499 // Emit information describing all of the types in the module.
1500 WriteTypeTable(VE, Stream);
1502 // Emit top-level description of module, including target triple, inline asm,
1503 // descriptors for global variables, and function prototype info.
1504 WriteModuleInfo(M, VE, Stream);
1507 WriteModuleConstants(VE, Stream);
1510 WriteModuleMetadata(M, VE, Stream);
1512 // Emit function bodies.
1513 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1514 if (!F->isDeclaration())
1515 WriteFunction(*F, VE, Stream);
1518 WriteModuleMetadataStore(M, Stream);
1520 // Emit the type symbol table information.
1521 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
1523 // Emit names for globals/functions etc.
1524 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1529 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1530 /// header and trailer to make it compatible with the system archiver. To do
1531 /// this we emit the following header, and then emit a trailer that pads the
1532 /// file out to be a multiple of 16 bytes.
1534 /// struct bc_header {
1535 /// uint32_t Magic; // 0x0B17C0DE
1536 /// uint32_t Version; // Version, currently always 0.
1537 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1538 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1539 /// uint32_t CPUType; // CPU specifier.
1540 /// ... potentially more later ...
1543 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1544 DarwinBCHeaderSize = 5*4
1547 static void EmitDarwinBCHeader(BitstreamWriter &Stream, const Triple &TT) {
1548 unsigned CPUType = ~0U;
1550 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1551 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1552 // number from /usr/include/mach/machine.h. It is ok to reproduce the
1553 // specific constants here because they are implicitly part of the Darwin ABI.
1555 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1556 DARWIN_CPU_TYPE_X86 = 7,
1557 DARWIN_CPU_TYPE_ARM = 12,
1558 DARWIN_CPU_TYPE_POWERPC = 18
1561 Triple::ArchType Arch = TT.getArch();
1562 if (Arch == Triple::x86_64)
1563 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1564 else if (Arch == Triple::x86)
1565 CPUType = DARWIN_CPU_TYPE_X86;
1566 else if (Arch == Triple::ppc)
1567 CPUType = DARWIN_CPU_TYPE_POWERPC;
1568 else if (Arch == Triple::ppc64)
1569 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1570 else if (Arch == Triple::arm || Arch == Triple::thumb)
1571 CPUType = DARWIN_CPU_TYPE_ARM;
1573 // Traditional Bitcode starts after header.
1574 unsigned BCOffset = DarwinBCHeaderSize;
1576 Stream.Emit(0x0B17C0DE, 32);
1577 Stream.Emit(0 , 32); // Version.
1578 Stream.Emit(BCOffset , 32);
1579 Stream.Emit(0 , 32); // Filled in later.
1580 Stream.Emit(CPUType , 32);
1583 /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
1584 /// finalize the header.
1585 static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
1586 // Update the size field in the header.
1587 Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
1589 // If the file is not a multiple of 16 bytes, insert dummy padding.
1590 while (BufferSize & 15) {
1597 /// WriteBitcodeToFile - Write the specified module to the specified output
1599 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1600 std::vector<unsigned char> Buffer;
1601 BitstreamWriter Stream(Buffer);
1603 Buffer.reserve(256*1024);
1605 WriteBitcodeToStream( M, Stream );
1607 // Write the generated bitstream to "Out".
1608 Out.write((char*)&Buffer.front(), Buffer.size());
1611 /// WriteBitcodeToStream - Write the specified module to the specified output
1613 void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
1614 // If this is darwin or another generic macho target, emit a file header and
1615 // trailer if needed.
1616 Triple TT(M->getTargetTriple());
1617 if (TT.isOSDarwin())
1618 EmitDarwinBCHeader(Stream, TT);
1620 // Emit the file header.
1621 Stream.Emit((unsigned)'B', 8);
1622 Stream.Emit((unsigned)'C', 8);
1623 Stream.Emit(0x0, 4);
1624 Stream.Emit(0xC, 4);
1625 Stream.Emit(0xE, 4);
1626 Stream.Emit(0xD, 4);
1629 WriteModule(M, Stream);
1631 if (TT.isOSDarwin())
1632 EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());