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/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"
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 unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
106 default: llvm_unreachable("Unknown RMW operation!");
107 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
108 case AtomicRMWInst::Add: return bitc::RMW_ADD;
109 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
110 case AtomicRMWInst::And: return bitc::RMW_AND;
111 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
112 case AtomicRMWInst::Or: return bitc::RMW_OR;
113 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
114 case AtomicRMWInst::Max: return bitc::RMW_MAX;
115 case AtomicRMWInst::Min: return bitc::RMW_MIN;
116 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
117 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
121 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
123 default: llvm_unreachable("Unknown atomic ordering");
124 case NotAtomic: return bitc::ORDERING_NOTATOMIC;
125 case Unordered: return bitc::ORDERING_UNORDERED;
126 case Monotonic: return bitc::ORDERING_MONOTONIC;
127 case Acquire: return bitc::ORDERING_ACQUIRE;
128 case Release: return bitc::ORDERING_RELEASE;
129 case AcquireRelease: return bitc::ORDERING_ACQREL;
130 case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
134 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
135 switch (SynchScope) {
136 default: llvm_unreachable("Unknown synchronization scope");
137 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
138 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
142 static void WriteStringRecord(unsigned Code, StringRef Str,
143 unsigned AbbrevToUse, BitstreamWriter &Stream) {
144 SmallVector<unsigned, 64> Vals;
146 // Code: [strchar x N]
147 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
148 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
150 Vals.push_back(Str[i]);
153 // Emit the finished record.
154 Stream.EmitRecord(Code, Vals, AbbrevToUse);
157 // Emit information about parameter attributes.
158 static void WriteAttributeTable(const ValueEnumerator &VE,
159 BitstreamWriter &Stream) {
160 const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
161 if (Attrs.empty()) return;
163 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
165 SmallVector<uint64_t, 64> Record;
166 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
167 const AttrListPtr &A = Attrs[i];
168 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
169 const AttributeWithIndex &PAWI = A.getSlot(i);
170 Record.push_back(PAWI.Index);
172 // FIXME: remove in LLVM 3.0
173 // Store the alignment in the bitcode as a 16-bit raw value instead of a
174 // 5-bit log2 encoded value. Shift the bits above the alignment up by
176 uint64_t FauxAttr = PAWI.Attrs & 0xffff;
177 if (PAWI.Attrs & Attribute::Alignment)
178 FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
179 FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
181 Record.push_back(FauxAttr);
184 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
191 /// WriteTypeTable - Write out the type table for a module.
192 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
193 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
195 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
196 SmallVector<uint64_t, 64> TypeVals;
198 // Abbrev for TYPE_CODE_POINTER.
199 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
200 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
201 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
202 Log2_32_Ceil(VE.getTypes().size()+1)));
203 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
204 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
206 // Abbrev for TYPE_CODE_FUNCTION.
207 Abbv = new BitCodeAbbrev();
208 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
209 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
210 Abbv->Add(BitCodeAbbrevOp(0)); // FIXME: DEAD value, remove in LLVM 3.0
211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
212 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
213 Log2_32_Ceil(VE.getTypes().size()+1)));
214 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
216 // Abbrev for TYPE_CODE_STRUCT_ANON.
217 Abbv = new BitCodeAbbrev();
218 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
219 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
220 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
221 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
222 Log2_32_Ceil(VE.getTypes().size()+1)));
223 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
225 // Abbrev for TYPE_CODE_STRUCT_NAME.
226 Abbv = new BitCodeAbbrev();
227 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
228 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
229 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
230 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
232 // Abbrev for TYPE_CODE_STRUCT_NAMED.
233 Abbv = new BitCodeAbbrev();
234 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
236 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
237 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
238 Log2_32_Ceil(VE.getTypes().size()+1)));
239 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
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);
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);
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];
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:
274 Code = bitc::TYPE_CODE_INTEGER;
275 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
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;
287 case Type::FunctionTyID: {
288 FunctionType *FT = cast<FunctionType>(T);
289 // FUNCTION: [isvararg, attrid, retty, paramty x N]
290 Code = bitc::TYPE_CODE_FUNCTION;
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;
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));
308 if (ST->isAnonymous()) {
309 Code = bitc::TYPE_CODE_STRUCT_ANON;
310 AbbrevToUse = StructAnonAbbrev;
312 if (ST->isOpaque()) {
313 Code = bitc::TYPE_CODE_OPAQUE;
315 Code = bitc::TYPE_CODE_STRUCT_NAMED;
316 AbbrevToUse = StructNamedAbbrev;
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);
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;
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()));
345 // Emit the finished record.
346 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
353 static unsigned getEncodedLinkage(const GlobalValue *GV) {
354 switch (GV->getLinkage()) {
355 default: llvm_unreachable("Invalid linkage!");
356 case GlobalValue::ExternalLinkage: return 0;
357 case GlobalValue::WeakAnyLinkage: return 1;
358 case GlobalValue::AppendingLinkage: return 2;
359 case GlobalValue::InternalLinkage: return 3;
360 case GlobalValue::LinkOnceAnyLinkage: return 4;
361 case GlobalValue::DLLImportLinkage: return 5;
362 case GlobalValue::DLLExportLinkage: return 6;
363 case GlobalValue::ExternalWeakLinkage: return 7;
364 case GlobalValue::CommonLinkage: return 8;
365 case GlobalValue::PrivateLinkage: return 9;
366 case GlobalValue::WeakODRLinkage: return 10;
367 case GlobalValue::LinkOnceODRLinkage: return 11;
368 case GlobalValue::AvailableExternallyLinkage: return 12;
369 case GlobalValue::LinkerPrivateLinkage: return 13;
370 case GlobalValue::LinkerPrivateWeakLinkage: return 14;
371 case GlobalValue::LinkerPrivateWeakDefAutoLinkage: return 15;
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;
384 // Emit top-level description of module, including target triple, inline asm,
385 // descriptors for global variables, and function prototype info.
386 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
387 BitstreamWriter &Stream) {
388 // Emit the list of dependent libraries for the Module.
389 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
390 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
392 // Emit various pieces of data attached to a module.
393 if (!M->getTargetTriple().empty())
394 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
396 if (!M->getDataLayout().empty())
397 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
399 if (!M->getModuleInlineAsm().empty())
400 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
403 // Emit information about sections and GC, computing how many there are. Also
404 // compute the maximum alignment value.
405 std::map<std::string, unsigned> SectionMap;
406 std::map<std::string, unsigned> GCMap;
407 unsigned MaxAlignment = 0;
408 unsigned MaxGlobalType = 0;
409 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
411 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
412 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
414 if (!GV->hasSection()) continue;
415 // Give section names unique ID's.
416 unsigned &Entry = SectionMap[GV->getSection()];
417 if (Entry != 0) continue;
418 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
420 Entry = SectionMap.size();
422 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
423 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
424 if (F->hasSection()) {
425 // Give section names unique ID's.
426 unsigned &Entry = SectionMap[F->getSection()];
428 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
430 Entry = SectionMap.size();
434 // Same for GC names.
435 unsigned &Entry = GCMap[F->getGC()];
437 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
439 Entry = GCMap.size();
444 // Emit abbrev for globals, now that we know # sections and max alignment.
445 unsigned SimpleGVarAbbrev = 0;
446 if (!M->global_empty()) {
447 // Add an abbrev for common globals with no visibility or thread localness.
448 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
449 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
450 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
451 Log2_32_Ceil(MaxGlobalType+1)));
452 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
453 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
454 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
455 if (MaxAlignment == 0) // Alignment.
456 Abbv->Add(BitCodeAbbrevOp(0));
458 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
459 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
460 Log2_32_Ceil(MaxEncAlignment+1)));
462 if (SectionMap.empty()) // Section.
463 Abbv->Add(BitCodeAbbrevOp(0));
465 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
466 Log2_32_Ceil(SectionMap.size()+1)));
467 // Don't bother emitting vis + thread local.
468 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
471 // Emit the global variable information.
472 SmallVector<unsigned, 64> Vals;
473 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
475 unsigned AbbrevToUse = 0;
477 // GLOBALVAR: [type, isconst, initid,
478 // linkage, alignment, section, visibility, threadlocal,
480 Vals.push_back(VE.getTypeID(GV->getType()));
481 Vals.push_back(GV->isConstant());
482 Vals.push_back(GV->isDeclaration() ? 0 :
483 (VE.getValueID(GV->getInitializer()) + 1));
484 Vals.push_back(getEncodedLinkage(GV));
485 Vals.push_back(Log2_32(GV->getAlignment())+1);
486 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
487 if (GV->isThreadLocal() ||
488 GV->getVisibility() != GlobalValue::DefaultVisibility ||
489 GV->hasUnnamedAddr()) {
490 Vals.push_back(getEncodedVisibility(GV));
491 Vals.push_back(GV->isThreadLocal());
492 Vals.push_back(GV->hasUnnamedAddr());
494 AbbrevToUse = SimpleGVarAbbrev;
497 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
501 // Emit the function proto information.
502 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
503 // FUNCTION: [type, callingconv, isproto, paramattr,
504 // linkage, alignment, section, visibility, gc, unnamed_addr]
505 Vals.push_back(VE.getTypeID(F->getType()));
506 Vals.push_back(F->getCallingConv());
507 Vals.push_back(F->isDeclaration());
508 Vals.push_back(getEncodedLinkage(F));
509 Vals.push_back(VE.getAttributeID(F->getAttributes()));
510 Vals.push_back(Log2_32(F->getAlignment())+1);
511 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
512 Vals.push_back(getEncodedVisibility(F));
513 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
514 Vals.push_back(F->hasUnnamedAddr());
516 unsigned AbbrevToUse = 0;
517 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
521 // Emit the alias information.
522 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
524 Vals.push_back(VE.getTypeID(AI->getType()));
525 Vals.push_back(VE.getValueID(AI->getAliasee()));
526 Vals.push_back(getEncodedLinkage(AI));
527 Vals.push_back(getEncodedVisibility(AI));
528 unsigned AbbrevToUse = 0;
529 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
534 static uint64_t GetOptimizationFlags(const Value *V) {
537 if (const OverflowingBinaryOperator *OBO =
538 dyn_cast<OverflowingBinaryOperator>(V)) {
539 if (OBO->hasNoSignedWrap())
540 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
541 if (OBO->hasNoUnsignedWrap())
542 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
543 } else if (const PossiblyExactOperator *PEO =
544 dyn_cast<PossiblyExactOperator>(V)) {
546 Flags |= 1 << bitc::PEO_EXACT;
552 static void WriteMDNode(const MDNode *N,
553 const ValueEnumerator &VE,
554 BitstreamWriter &Stream,
555 SmallVector<uint64_t, 64> &Record) {
556 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
557 if (N->getOperand(i)) {
558 Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
559 Record.push_back(VE.getValueID(N->getOperand(i)));
561 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
565 unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
567 Stream.EmitRecord(MDCode, Record, 0);
571 static void WriteModuleMetadata(const Module *M,
572 const ValueEnumerator &VE,
573 BitstreamWriter &Stream) {
574 const ValueEnumerator::ValueList &Vals = VE.getMDValues();
575 bool StartedMetadataBlock = false;
576 unsigned MDSAbbrev = 0;
577 SmallVector<uint64_t, 64> Record;
578 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
580 if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
581 if (!N->isFunctionLocal() || !N->getFunction()) {
582 if (!StartedMetadataBlock) {
583 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
584 StartedMetadataBlock = true;
586 WriteMDNode(N, VE, Stream, Record);
588 } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
589 if (!StartedMetadataBlock) {
590 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
592 // Abbrev for METADATA_STRING.
593 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
594 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
595 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
596 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
597 MDSAbbrev = Stream.EmitAbbrev(Abbv);
598 StartedMetadataBlock = true;
601 // Code: [strchar x N]
602 Record.append(MDS->begin(), MDS->end());
604 // Emit the finished record.
605 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
610 // Write named metadata.
611 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
612 E = M->named_metadata_end(); I != E; ++I) {
613 const NamedMDNode *NMD = I;
614 if (!StartedMetadataBlock) {
615 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
616 StartedMetadataBlock = true;
620 StringRef Str = NMD->getName();
621 for (unsigned i = 0, e = Str.size(); i != e; ++i)
622 Record.push_back(Str[i]);
623 Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
626 // Write named metadata operands.
627 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
628 Record.push_back(VE.getValueID(NMD->getOperand(i)));
629 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
633 if (StartedMetadataBlock)
637 static void WriteFunctionLocalMetadata(const Function &F,
638 const ValueEnumerator &VE,
639 BitstreamWriter &Stream) {
640 bool StartedMetadataBlock = false;
641 SmallVector<uint64_t, 64> Record;
642 const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues();
643 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
644 if (const MDNode *N = Vals[i])
645 if (N->isFunctionLocal() && N->getFunction() == &F) {
646 if (!StartedMetadataBlock) {
647 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
648 StartedMetadataBlock = true;
650 WriteMDNode(N, VE, Stream, Record);
653 if (StartedMetadataBlock)
657 static void WriteMetadataAttachment(const Function &F,
658 const ValueEnumerator &VE,
659 BitstreamWriter &Stream) {
660 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
662 SmallVector<uint64_t, 64> Record;
664 // Write metadata attachments
665 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
666 SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
668 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
669 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
672 I->getAllMetadataOtherThanDebugLoc(MDs);
674 // If no metadata, ignore instruction.
675 if (MDs.empty()) continue;
677 Record.push_back(VE.getInstructionID(I));
679 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
680 Record.push_back(MDs[i].first);
681 Record.push_back(VE.getValueID(MDs[i].second));
683 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
690 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
691 SmallVector<uint64_t, 64> Record;
693 // Write metadata kinds
694 // METADATA_KIND - [n x [id, name]]
695 SmallVector<StringRef, 4> Names;
696 M->getMDKindNames(Names);
698 if (Names.empty()) return;
700 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
702 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
703 Record.push_back(MDKindID);
704 StringRef KName = Names[MDKindID];
705 Record.append(KName.begin(), KName.end());
707 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
714 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
715 const ValueEnumerator &VE,
716 BitstreamWriter &Stream, bool isGlobal) {
717 if (FirstVal == LastVal) return;
719 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
721 unsigned AggregateAbbrev = 0;
722 unsigned String8Abbrev = 0;
723 unsigned CString7Abbrev = 0;
724 unsigned CString6Abbrev = 0;
725 // If this is a constant pool for the module, emit module-specific abbrevs.
727 // Abbrev for CST_CODE_AGGREGATE.
728 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
729 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
730 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
731 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
732 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
734 // Abbrev for CST_CODE_STRING.
735 Abbv = new BitCodeAbbrev();
736 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
737 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
738 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
739 String8Abbrev = Stream.EmitAbbrev(Abbv);
740 // Abbrev for CST_CODE_CSTRING.
741 Abbv = new BitCodeAbbrev();
742 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
743 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
744 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
745 CString7Abbrev = Stream.EmitAbbrev(Abbv);
746 // Abbrev for CST_CODE_CSTRING.
747 Abbv = new BitCodeAbbrev();
748 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
749 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
750 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
751 CString6Abbrev = Stream.EmitAbbrev(Abbv);
754 SmallVector<uint64_t, 64> Record;
756 const ValueEnumerator::ValueList &Vals = VE.getValues();
758 for (unsigned i = FirstVal; i != LastVal; ++i) {
759 const Value *V = Vals[i].first;
760 // If we need to switch types, do so now.
761 if (V->getType() != LastTy) {
762 LastTy = V->getType();
763 Record.push_back(VE.getTypeID(LastTy));
764 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
765 CONSTANTS_SETTYPE_ABBREV);
769 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
770 Record.push_back(unsigned(IA->hasSideEffects()) |
771 unsigned(IA->isAlignStack()) << 1);
773 // Add the asm string.
774 const std::string &AsmStr = IA->getAsmString();
775 Record.push_back(AsmStr.size());
776 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
777 Record.push_back(AsmStr[i]);
779 // Add the constraint string.
780 const std::string &ConstraintStr = IA->getConstraintString();
781 Record.push_back(ConstraintStr.size());
782 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
783 Record.push_back(ConstraintStr[i]);
784 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
788 const Constant *C = cast<Constant>(V);
790 unsigned AbbrevToUse = 0;
791 if (C->isNullValue()) {
792 Code = bitc::CST_CODE_NULL;
793 } else if (isa<UndefValue>(C)) {
794 Code = bitc::CST_CODE_UNDEF;
795 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
796 if (IV->getBitWidth() <= 64) {
797 uint64_t V = IV->getSExtValue();
799 Record.push_back(V << 1);
801 Record.push_back((-V << 1) | 1);
802 Code = bitc::CST_CODE_INTEGER;
803 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
804 } else { // Wide integers, > 64 bits in size.
805 // We have an arbitrary precision integer value to write whose
806 // bit width is > 64. However, in canonical unsigned integer
807 // format it is likely that the high bits are going to be zero.
808 // So, we only write the number of active words.
809 unsigned NWords = IV->getValue().getActiveWords();
810 const uint64_t *RawWords = IV->getValue().getRawData();
811 for (unsigned i = 0; i != NWords; ++i) {
812 int64_t V = RawWords[i];
814 Record.push_back(V << 1);
816 Record.push_back((-V << 1) | 1);
818 Code = bitc::CST_CODE_WIDE_INTEGER;
820 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
821 Code = bitc::CST_CODE_FLOAT;
822 Type *Ty = CFP->getType();
823 if (Ty->isFloatTy() || Ty->isDoubleTy()) {
824 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
825 } else if (Ty->isX86_FP80Ty()) {
826 // api needed to prevent premature destruction
827 // bits are not in the same order as a normal i80 APInt, compensate.
828 APInt api = CFP->getValueAPF().bitcastToAPInt();
829 const uint64_t *p = api.getRawData();
830 Record.push_back((p[1] << 48) | (p[0] >> 16));
831 Record.push_back(p[0] & 0xffffLL);
832 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
833 APInt api = CFP->getValueAPF().bitcastToAPInt();
834 const uint64_t *p = api.getRawData();
835 Record.push_back(p[0]);
836 Record.push_back(p[1]);
838 assert (0 && "Unknown FP type!");
840 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
841 const ConstantArray *CA = cast<ConstantArray>(C);
842 // Emit constant strings specially.
843 unsigned NumOps = CA->getNumOperands();
844 // If this is a null-terminated string, use the denser CSTRING encoding.
845 if (CA->getOperand(NumOps-1)->isNullValue()) {
846 Code = bitc::CST_CODE_CSTRING;
847 --NumOps; // Don't encode the null, which isn't allowed by char6.
849 Code = bitc::CST_CODE_STRING;
850 AbbrevToUse = String8Abbrev;
852 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
853 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
854 for (unsigned i = 0; i != NumOps; ++i) {
855 unsigned char V = cast<ConstantInt>(CA->getOperand(i))->getZExtValue();
857 isCStr7 &= (V & 128) == 0;
859 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
863 AbbrevToUse = CString6Abbrev;
865 AbbrevToUse = CString7Abbrev;
866 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
867 isa<ConstantVector>(V)) {
868 Code = bitc::CST_CODE_AGGREGATE;
869 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
870 Record.push_back(VE.getValueID(C->getOperand(i)));
871 AbbrevToUse = AggregateAbbrev;
872 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
873 switch (CE->getOpcode()) {
875 if (Instruction::isCast(CE->getOpcode())) {
876 Code = bitc::CST_CODE_CE_CAST;
877 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
878 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
879 Record.push_back(VE.getValueID(C->getOperand(0)));
880 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
882 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
883 Code = bitc::CST_CODE_CE_BINOP;
884 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
885 Record.push_back(VE.getValueID(C->getOperand(0)));
886 Record.push_back(VE.getValueID(C->getOperand(1)));
887 uint64_t Flags = GetOptimizationFlags(CE);
889 Record.push_back(Flags);
892 case Instruction::GetElementPtr:
893 Code = bitc::CST_CODE_CE_GEP;
894 if (cast<GEPOperator>(C)->isInBounds())
895 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
896 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
897 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
898 Record.push_back(VE.getValueID(C->getOperand(i)));
901 case Instruction::Select:
902 Code = bitc::CST_CODE_CE_SELECT;
903 Record.push_back(VE.getValueID(C->getOperand(0)));
904 Record.push_back(VE.getValueID(C->getOperand(1)));
905 Record.push_back(VE.getValueID(C->getOperand(2)));
907 case Instruction::ExtractElement:
908 Code = bitc::CST_CODE_CE_EXTRACTELT;
909 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
910 Record.push_back(VE.getValueID(C->getOperand(0)));
911 Record.push_back(VE.getValueID(C->getOperand(1)));
913 case Instruction::InsertElement:
914 Code = bitc::CST_CODE_CE_INSERTELT;
915 Record.push_back(VE.getValueID(C->getOperand(0)));
916 Record.push_back(VE.getValueID(C->getOperand(1)));
917 Record.push_back(VE.getValueID(C->getOperand(2)));
919 case Instruction::ShuffleVector:
920 // If the return type and argument types are the same, this is a
921 // standard shufflevector instruction. If the types are different,
922 // then the shuffle is widening or truncating the input vectors, and
923 // the argument type must also be encoded.
924 if (C->getType() == C->getOperand(0)->getType()) {
925 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
927 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
928 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
930 Record.push_back(VE.getValueID(C->getOperand(0)));
931 Record.push_back(VE.getValueID(C->getOperand(1)));
932 Record.push_back(VE.getValueID(C->getOperand(2)));
934 case Instruction::ICmp:
935 case Instruction::FCmp:
936 Code = bitc::CST_CODE_CE_CMP;
937 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
938 Record.push_back(VE.getValueID(C->getOperand(0)));
939 Record.push_back(VE.getValueID(C->getOperand(1)));
940 Record.push_back(CE->getPredicate());
943 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
944 Code = bitc::CST_CODE_BLOCKADDRESS;
945 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
946 Record.push_back(VE.getValueID(BA->getFunction()));
947 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
952 llvm_unreachable("Unknown constant!");
954 Stream.EmitRecord(Code, Record, AbbrevToUse);
961 static void WriteModuleConstants(const ValueEnumerator &VE,
962 BitstreamWriter &Stream) {
963 const ValueEnumerator::ValueList &Vals = VE.getValues();
965 // Find the first constant to emit, which is the first non-globalvalue value.
966 // We know globalvalues have been emitted by WriteModuleInfo.
967 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
968 if (!isa<GlobalValue>(Vals[i].first)) {
969 WriteConstants(i, Vals.size(), VE, Stream, true);
975 /// PushValueAndType - The file has to encode both the value and type id for
976 /// many values, because we need to know what type to create for forward
977 /// references. However, most operands are not forward references, so this type
978 /// field is not needed.
980 /// This function adds V's value ID to Vals. If the value ID is higher than the
981 /// instruction ID, then it is a forward reference, and it also includes the
983 static bool PushValueAndType(const Value *V, unsigned InstID,
984 SmallVector<unsigned, 64> &Vals,
985 ValueEnumerator &VE) {
986 unsigned ValID = VE.getValueID(V);
987 Vals.push_back(ValID);
988 if (ValID >= InstID) {
989 Vals.push_back(VE.getTypeID(V->getType()));
995 /// WriteInstruction - Emit an instruction to the specified stream.
996 static void WriteInstruction(const Instruction &I, unsigned InstID,
997 ValueEnumerator &VE, BitstreamWriter &Stream,
998 SmallVector<unsigned, 64> &Vals) {
1000 unsigned AbbrevToUse = 0;
1001 VE.setInstructionID(&I);
1002 switch (I.getOpcode()) {
1004 if (Instruction::isCast(I.getOpcode())) {
1005 Code = bitc::FUNC_CODE_INST_CAST;
1006 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1007 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1008 Vals.push_back(VE.getTypeID(I.getType()));
1009 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1011 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1012 Code = bitc::FUNC_CODE_INST_BINOP;
1013 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1014 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1015 Vals.push_back(VE.getValueID(I.getOperand(1)));
1016 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1017 uint64_t Flags = GetOptimizationFlags(&I);
1019 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1020 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1021 Vals.push_back(Flags);
1026 case Instruction::GetElementPtr:
1027 Code = bitc::FUNC_CODE_INST_GEP;
1028 if (cast<GEPOperator>(&I)->isInBounds())
1029 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1030 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1031 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1033 case Instruction::ExtractValue: {
1034 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1035 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1036 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1037 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1041 case Instruction::InsertValue: {
1042 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1043 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1044 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1045 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1046 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1050 case Instruction::Select:
1051 Code = bitc::FUNC_CODE_INST_VSELECT;
1052 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1053 Vals.push_back(VE.getValueID(I.getOperand(2)));
1054 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1056 case Instruction::ExtractElement:
1057 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1058 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1059 Vals.push_back(VE.getValueID(I.getOperand(1)));
1061 case Instruction::InsertElement:
1062 Code = bitc::FUNC_CODE_INST_INSERTELT;
1063 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1064 Vals.push_back(VE.getValueID(I.getOperand(1)));
1065 Vals.push_back(VE.getValueID(I.getOperand(2)));
1067 case Instruction::ShuffleVector:
1068 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1069 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1070 Vals.push_back(VE.getValueID(I.getOperand(1)));
1071 Vals.push_back(VE.getValueID(I.getOperand(2)));
1073 case Instruction::ICmp:
1074 case Instruction::FCmp:
1075 // compare returning Int1Ty or vector of Int1Ty
1076 Code = bitc::FUNC_CODE_INST_CMP2;
1077 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1078 Vals.push_back(VE.getValueID(I.getOperand(1)));
1079 Vals.push_back(cast<CmpInst>(I).getPredicate());
1082 case Instruction::Ret:
1084 Code = bitc::FUNC_CODE_INST_RET;
1085 unsigned NumOperands = I.getNumOperands();
1086 if (NumOperands == 0)
1087 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1088 else if (NumOperands == 1) {
1089 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1090 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1092 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1093 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1097 case Instruction::Br:
1099 Code = bitc::FUNC_CODE_INST_BR;
1100 BranchInst &II = cast<BranchInst>(I);
1101 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1102 if (II.isConditional()) {
1103 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1104 Vals.push_back(VE.getValueID(II.getCondition()));
1108 case Instruction::Switch:
1109 Code = bitc::FUNC_CODE_INST_SWITCH;
1110 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1111 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1112 Vals.push_back(VE.getValueID(I.getOperand(i)));
1114 case Instruction::IndirectBr:
1115 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1116 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1117 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1118 Vals.push_back(VE.getValueID(I.getOperand(i)));
1121 case Instruction::Invoke: {
1122 const InvokeInst *II = cast<InvokeInst>(&I);
1123 const Value *Callee(II->getCalledValue());
1124 PointerType *PTy = cast<PointerType>(Callee->getType());
1125 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1126 Code = bitc::FUNC_CODE_INST_INVOKE;
1128 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1129 Vals.push_back(II->getCallingConv());
1130 Vals.push_back(VE.getValueID(II->getNormalDest()));
1131 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1132 PushValueAndType(Callee, InstID, Vals, VE);
1134 // Emit value #'s for the fixed parameters.
1135 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1136 Vals.push_back(VE.getValueID(I.getOperand(i))); // fixed param.
1138 // Emit type/value pairs for varargs params.
1139 if (FTy->isVarArg()) {
1140 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1142 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1146 case Instruction::Resume:
1147 Code = bitc::FUNC_CODE_INST_RESUME;
1148 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1150 case Instruction::Unwind:
1151 Code = bitc::FUNC_CODE_INST_UNWIND;
1153 case Instruction::Unreachable:
1154 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1155 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1158 case Instruction::PHI: {
1159 const PHINode &PN = cast<PHINode>(I);
1160 Code = bitc::FUNC_CODE_INST_PHI;
1161 Vals.push_back(VE.getTypeID(PN.getType()));
1162 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1163 Vals.push_back(VE.getValueID(PN.getIncomingValue(i)));
1164 Vals.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1169 case Instruction::Alloca:
1170 Code = bitc::FUNC_CODE_INST_ALLOCA;
1171 Vals.push_back(VE.getTypeID(I.getType()));
1172 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1173 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1174 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1177 case Instruction::Load:
1178 Code = bitc::FUNC_CODE_INST_LOAD;
1179 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1180 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1182 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1183 Vals.push_back(cast<LoadInst>(I).isVolatile());
1185 case Instruction::Store:
1186 Code = bitc::FUNC_CODE_INST_STORE;
1187 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1188 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
1189 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1190 Vals.push_back(cast<StoreInst>(I).isVolatile());
1192 case Instruction::AtomicCmpXchg:
1193 Code = bitc::FUNC_CODE_INST_CMPXCHG;
1194 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1195 Vals.push_back(VE.getValueID(I.getOperand(1))); // cmp.
1196 Vals.push_back(VE.getValueID(I.getOperand(2))); // newval.
1197 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1198 Vals.push_back(GetEncodedOrdering(
1199 cast<AtomicCmpXchgInst>(I).getOrdering()));
1200 Vals.push_back(GetEncodedSynchScope(
1201 cast<AtomicCmpXchgInst>(I).getSynchScope()));
1203 case Instruction::AtomicRMW:
1204 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1205 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1206 Vals.push_back(VE.getValueID(I.getOperand(1))); // val.
1207 Vals.push_back(GetEncodedRMWOperation(
1208 cast<AtomicRMWInst>(I).getOperation()));
1209 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1210 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1211 Vals.push_back(GetEncodedSynchScope(
1212 cast<AtomicRMWInst>(I).getSynchScope()));
1214 case Instruction::Fence:
1215 Code = bitc::FUNC_CODE_INST_FENCE;
1216 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1217 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1219 case Instruction::Call: {
1220 const CallInst &CI = cast<CallInst>(I);
1221 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1222 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1224 Code = bitc::FUNC_CODE_INST_CALL;
1226 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1227 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1228 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1230 // Emit value #'s for the fixed parameters.
1231 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1232 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); // fixed param.
1234 // Emit type/value pairs for varargs params.
1235 if (FTy->isVarArg()) {
1236 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1238 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1242 case Instruction::VAArg:
1243 Code = bitc::FUNC_CODE_INST_VAARG;
1244 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1245 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
1246 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1250 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1254 // Emit names for globals/functions etc.
1255 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1256 const ValueEnumerator &VE,
1257 BitstreamWriter &Stream) {
1258 if (VST.empty()) return;
1259 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1261 // FIXME: Set up the abbrev, we know how many values there are!
1262 // FIXME: We know if the type names can use 7-bit ascii.
1263 SmallVector<unsigned, 64> NameVals;
1265 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1268 const ValueName &Name = *SI;
1270 // Figure out the encoding to use for the name.
1272 bool isChar6 = true;
1273 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1276 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1277 if ((unsigned char)*C & 128) {
1279 break; // don't bother scanning the rest.
1283 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1285 // VST_ENTRY: [valueid, namechar x N]
1286 // VST_BBENTRY: [bbid, namechar x N]
1288 if (isa<BasicBlock>(SI->getValue())) {
1289 Code = bitc::VST_CODE_BBENTRY;
1291 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1293 Code = bitc::VST_CODE_ENTRY;
1295 AbbrevToUse = VST_ENTRY_6_ABBREV;
1297 AbbrevToUse = VST_ENTRY_7_ABBREV;
1300 NameVals.push_back(VE.getValueID(SI->getValue()));
1301 for (const char *P = Name.getKeyData(),
1302 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1303 NameVals.push_back((unsigned char)*P);
1305 // Emit the finished record.
1306 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1312 /// WriteFunction - Emit a function body to the module stream.
1313 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1314 BitstreamWriter &Stream) {
1315 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1316 VE.incorporateFunction(F);
1318 SmallVector<unsigned, 64> Vals;
1320 // Emit the number of basic blocks, so the reader can create them ahead of
1322 Vals.push_back(VE.getBasicBlocks().size());
1323 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1326 // If there are function-local constants, emit them now.
1327 unsigned CstStart, CstEnd;
1328 VE.getFunctionConstantRange(CstStart, CstEnd);
1329 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1331 // If there is function-local metadata, emit it now.
1332 WriteFunctionLocalMetadata(F, VE, Stream);
1334 // Keep a running idea of what the instruction ID is.
1335 unsigned InstID = CstEnd;
1337 bool NeedsMetadataAttachment = false;
1341 // Finally, emit all the instructions, in order.
1342 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1343 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1345 WriteInstruction(*I, InstID, VE, Stream, Vals);
1347 if (!I->getType()->isVoidTy())
1350 // If the instruction has metadata, write a metadata attachment later.
1351 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1353 // If the instruction has a debug location, emit it.
1354 DebugLoc DL = I->getDebugLoc();
1355 if (DL.isUnknown()) {
1357 } else if (DL == LastDL) {
1358 // Just repeat the same debug loc as last time.
1359 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1362 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1364 Vals.push_back(DL.getLine());
1365 Vals.push_back(DL.getCol());
1366 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1367 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1368 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1375 // Emit names for all the instructions etc.
1376 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1378 if (NeedsMetadataAttachment)
1379 WriteMetadataAttachment(F, VE, Stream);
1384 // Emit blockinfo, which defines the standard abbreviations etc.
1385 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1386 // We only want to emit block info records for blocks that have multiple
1387 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
1388 // blocks can defined their abbrevs inline.
1389 Stream.EnterBlockInfoBlock(2);
1391 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1392 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1393 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1394 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1395 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1396 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1397 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1398 Abbv) != VST_ENTRY_8_ABBREV)
1399 llvm_unreachable("Unexpected abbrev ordering!");
1402 { // 7-bit fixed width VST_ENTRY strings.
1403 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1404 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1405 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1406 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1407 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1408 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1409 Abbv) != VST_ENTRY_7_ABBREV)
1410 llvm_unreachable("Unexpected abbrev ordering!");
1412 { // 6-bit char6 VST_ENTRY strings.
1413 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1414 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1415 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1416 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1417 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1418 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1419 Abbv) != VST_ENTRY_6_ABBREV)
1420 llvm_unreachable("Unexpected abbrev ordering!");
1422 { // 6-bit char6 VST_BBENTRY strings.
1423 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1424 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1425 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1426 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1427 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1428 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1429 Abbv) != VST_BBENTRY_6_ABBREV)
1430 llvm_unreachable("Unexpected abbrev ordering!");
1435 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1436 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1437 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1438 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1439 Log2_32_Ceil(VE.getTypes().size()+1)));
1440 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1441 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1442 llvm_unreachable("Unexpected abbrev ordering!");
1445 { // INTEGER abbrev for CONSTANTS_BLOCK.
1446 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1447 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1449 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1450 Abbv) != CONSTANTS_INTEGER_ABBREV)
1451 llvm_unreachable("Unexpected abbrev ordering!");
1454 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1455 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1456 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1457 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1458 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1459 Log2_32_Ceil(VE.getTypes().size()+1)));
1460 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1462 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1463 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1464 llvm_unreachable("Unexpected abbrev ordering!");
1466 { // NULL abbrev for CONSTANTS_BLOCK.
1467 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1468 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1469 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1470 Abbv) != CONSTANTS_NULL_Abbrev)
1471 llvm_unreachable("Unexpected abbrev ordering!");
1474 // FIXME: This should only use space for first class types!
1476 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1477 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1478 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1479 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1480 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1481 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1482 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1483 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1484 llvm_unreachable("Unexpected abbrev ordering!");
1486 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1487 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1488 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1489 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1490 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1491 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1492 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1493 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1494 llvm_unreachable("Unexpected abbrev ordering!");
1496 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1497 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1498 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1499 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1500 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1501 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1502 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1503 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1504 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1505 llvm_unreachable("Unexpected abbrev ordering!");
1507 { // INST_CAST abbrev for FUNCTION_BLOCK.
1508 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1509 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1510 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1511 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1512 Log2_32_Ceil(VE.getTypes().size()+1)));
1513 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1514 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1515 Abbv) != FUNCTION_INST_CAST_ABBREV)
1516 llvm_unreachable("Unexpected abbrev ordering!");
1519 { // INST_RET abbrev for FUNCTION_BLOCK.
1520 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1521 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1522 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1523 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1524 llvm_unreachable("Unexpected abbrev ordering!");
1526 { // INST_RET abbrev for FUNCTION_BLOCK.
1527 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1528 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1529 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1530 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1531 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1532 llvm_unreachable("Unexpected abbrev ordering!");
1534 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1535 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1536 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1537 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1538 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1539 llvm_unreachable("Unexpected abbrev ordering!");
1546 /// WriteModule - Emit the specified module to the bitstream.
1547 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1548 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1550 // Emit the version number if it is non-zero.
1552 SmallVector<unsigned, 1> Vals;
1553 Vals.push_back(CurVersion);
1554 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1557 // Analyze the module, enumerating globals, functions, etc.
1558 ValueEnumerator VE(M);
1560 // Emit blockinfo, which defines the standard abbreviations etc.
1561 WriteBlockInfo(VE, Stream);
1563 // Emit information about parameter attributes.
1564 WriteAttributeTable(VE, Stream);
1566 // Emit information describing all of the types in the module.
1567 WriteTypeTable(VE, Stream);
1569 // Emit top-level description of module, including target triple, inline asm,
1570 // descriptors for global variables, and function prototype info.
1571 WriteModuleInfo(M, VE, Stream);
1574 WriteModuleConstants(VE, Stream);
1577 WriteModuleMetadata(M, VE, Stream);
1579 // Emit function bodies.
1580 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1581 if (!F->isDeclaration())
1582 WriteFunction(*F, VE, Stream);
1585 WriteModuleMetadataStore(M, Stream);
1587 // Emit names for globals/functions etc.
1588 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1593 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1594 /// header and trailer to make it compatible with the system archiver. To do
1595 /// this we emit the following header, and then emit a trailer that pads the
1596 /// file out to be a multiple of 16 bytes.
1598 /// struct bc_header {
1599 /// uint32_t Magic; // 0x0B17C0DE
1600 /// uint32_t Version; // Version, currently always 0.
1601 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1602 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1603 /// uint32_t CPUType; // CPU specifier.
1604 /// ... potentially more later ...
1607 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1608 DarwinBCHeaderSize = 5*4
1611 static void EmitDarwinBCHeader(BitstreamWriter &Stream, const Triple &TT) {
1612 unsigned CPUType = ~0U;
1614 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1615 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1616 // number from /usr/include/mach/machine.h. It is ok to reproduce the
1617 // specific constants here because they are implicitly part of the Darwin ABI.
1619 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1620 DARWIN_CPU_TYPE_X86 = 7,
1621 DARWIN_CPU_TYPE_ARM = 12,
1622 DARWIN_CPU_TYPE_POWERPC = 18
1625 Triple::ArchType Arch = TT.getArch();
1626 if (Arch == Triple::x86_64)
1627 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1628 else if (Arch == Triple::x86)
1629 CPUType = DARWIN_CPU_TYPE_X86;
1630 else if (Arch == Triple::ppc)
1631 CPUType = DARWIN_CPU_TYPE_POWERPC;
1632 else if (Arch == Triple::ppc64)
1633 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1634 else if (Arch == Triple::arm || Arch == Triple::thumb)
1635 CPUType = DARWIN_CPU_TYPE_ARM;
1637 // Traditional Bitcode starts after header.
1638 unsigned BCOffset = DarwinBCHeaderSize;
1640 Stream.Emit(0x0B17C0DE, 32);
1641 Stream.Emit(0 , 32); // Version.
1642 Stream.Emit(BCOffset , 32);
1643 Stream.Emit(0 , 32); // Filled in later.
1644 Stream.Emit(CPUType , 32);
1647 /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
1648 /// finalize the header.
1649 static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
1650 // Update the size field in the header.
1651 Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
1653 // If the file is not a multiple of 16 bytes, insert dummy padding.
1654 while (BufferSize & 15) {
1661 /// WriteBitcodeToFile - Write the specified module to the specified output
1663 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1664 std::vector<unsigned char> Buffer;
1665 BitstreamWriter Stream(Buffer);
1667 Buffer.reserve(256*1024);
1669 WriteBitcodeToStream( M, Stream );
1671 // Write the generated bitstream to "Out".
1672 Out.write((char*)&Buffer.front(), Buffer.size());
1675 /// WriteBitcodeToStream - Write the specified module to the specified output
1677 void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
1678 // If this is darwin or another generic macho target, emit a file header and
1679 // trailer if needed.
1680 Triple TT(M->getTargetTriple());
1681 if (TT.isOSDarwin())
1682 EmitDarwinBCHeader(Stream, TT);
1684 // Emit the file header.
1685 Stream.Emit((unsigned)'B', 8);
1686 Stream.Emit((unsigned)'C', 8);
1687 Stream.Emit(0x0, 4);
1688 Stream.Emit(0xC, 4);
1689 Stream.Emit(0xE, 4);
1690 Stream.Emit(0xD, 4);
1693 WriteModule(M, Stream);
1695 if (TT.isOSDarwin())
1696 EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());