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/CommandLine.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Support/Program.h"
36 EnablePreserveUseListOrdering("enable-bc-uselist-preserve",
37 cl::desc("Turn on experimental support for "
38 "use-list order preservation."),
39 cl::init(false), cl::Hidden);
41 /// These are manifest constants used by the bitcode writer. They do not need to
42 /// be kept in sync with the reader, but need to be consistent within this file.
46 // VALUE_SYMTAB_BLOCK abbrev id's.
47 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
52 // CONSTANTS_BLOCK abbrev id's.
53 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
54 CONSTANTS_INTEGER_ABBREV,
55 CONSTANTS_CE_CAST_Abbrev,
56 CONSTANTS_NULL_Abbrev,
58 // FUNCTION_BLOCK abbrev id's.
59 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
60 FUNCTION_INST_BINOP_ABBREV,
61 FUNCTION_INST_BINOP_FLAGS_ABBREV,
62 FUNCTION_INST_CAST_ABBREV,
63 FUNCTION_INST_RET_VOID_ABBREV,
64 FUNCTION_INST_RET_VAL_ABBREV,
65 FUNCTION_INST_UNREACHABLE_ABBREV,
68 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
71 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
73 default: llvm_unreachable("Unknown cast instruction!");
74 case Instruction::Trunc : return bitc::CAST_TRUNC;
75 case Instruction::ZExt : return bitc::CAST_ZEXT;
76 case Instruction::SExt : return bitc::CAST_SEXT;
77 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
78 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
79 case Instruction::UIToFP : return bitc::CAST_UITOFP;
80 case Instruction::SIToFP : return bitc::CAST_SITOFP;
81 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
82 case Instruction::FPExt : return bitc::CAST_FPEXT;
83 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
84 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
85 case Instruction::BitCast : return bitc::CAST_BITCAST;
89 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
91 default: llvm_unreachable("Unknown binary instruction!");
92 case Instruction::Add:
93 case Instruction::FAdd: return bitc::BINOP_ADD;
94 case Instruction::Sub:
95 case Instruction::FSub: return bitc::BINOP_SUB;
96 case Instruction::Mul:
97 case Instruction::FMul: return bitc::BINOP_MUL;
98 case Instruction::UDiv: return bitc::BINOP_UDIV;
99 case Instruction::FDiv:
100 case Instruction::SDiv: return bitc::BINOP_SDIV;
101 case Instruction::URem: return bitc::BINOP_UREM;
102 case Instruction::FRem:
103 case Instruction::SRem: return bitc::BINOP_SREM;
104 case Instruction::Shl: return bitc::BINOP_SHL;
105 case Instruction::LShr: return bitc::BINOP_LSHR;
106 case Instruction::AShr: return bitc::BINOP_ASHR;
107 case Instruction::And: return bitc::BINOP_AND;
108 case Instruction::Or: return bitc::BINOP_OR;
109 case Instruction::Xor: return bitc::BINOP_XOR;
113 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
115 default: llvm_unreachable("Unknown RMW operation!");
116 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
117 case AtomicRMWInst::Add: return bitc::RMW_ADD;
118 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
119 case AtomicRMWInst::And: return bitc::RMW_AND;
120 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
121 case AtomicRMWInst::Or: return bitc::RMW_OR;
122 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
123 case AtomicRMWInst::Max: return bitc::RMW_MAX;
124 case AtomicRMWInst::Min: return bitc::RMW_MIN;
125 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
126 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
130 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
132 case NotAtomic: return bitc::ORDERING_NOTATOMIC;
133 case Unordered: return bitc::ORDERING_UNORDERED;
134 case Monotonic: return bitc::ORDERING_MONOTONIC;
135 case Acquire: return bitc::ORDERING_ACQUIRE;
136 case Release: return bitc::ORDERING_RELEASE;
137 case AcquireRelease: return bitc::ORDERING_ACQREL;
138 case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
140 llvm_unreachable("Invalid ordering");
143 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
144 switch (SynchScope) {
145 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
146 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
148 llvm_unreachable("Invalid synch scope");
151 static void WriteStringRecord(unsigned Code, StringRef Str,
152 unsigned AbbrevToUse, BitstreamWriter &Stream) {
153 SmallVector<unsigned, 64> Vals;
155 // Code: [strchar x N]
156 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
157 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
159 Vals.push_back(Str[i]);
162 // Emit the finished record.
163 Stream.EmitRecord(Code, Vals, AbbrevToUse);
166 // Emit information about parameter attributes.
167 static void WriteAttributeTable(const ValueEnumerator &VE,
168 BitstreamWriter &Stream) {
169 const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
170 if (Attrs.empty()) return;
172 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
174 SmallVector<uint64_t, 64> Record;
175 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
176 const AttrListPtr &A = Attrs[i];
177 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
178 const AttributeWithIndex &PAWI = A.getSlot(i);
179 Record.push_back(PAWI.Index);
180 Record.push_back(Attribute::encodeLLVMAttributesForBitcode(PAWI.Attrs));
183 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
190 /// WriteTypeTable - Write out the type table for a module.
191 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
192 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
194 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
195 SmallVector<uint64_t, 64> TypeVals;
197 uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
199 // Abbrev for TYPE_CODE_POINTER.
200 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
201 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
202 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
203 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
204 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
206 // Abbrev for TYPE_CODE_FUNCTION.
207 Abbv = new BitCodeAbbrev();
208 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
209 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
210 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
213 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
215 // Abbrev for TYPE_CODE_STRUCT_ANON.
216 Abbv = new BitCodeAbbrev();
217 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
218 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
219 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
220 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
222 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
224 // Abbrev for TYPE_CODE_STRUCT_NAME.
225 Abbv = new BitCodeAbbrev();
226 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
227 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
228 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
229 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
231 // Abbrev for TYPE_CODE_STRUCT_NAMED.
232 Abbv = new BitCodeAbbrev();
233 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
236 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
238 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
240 // Abbrev for TYPE_CODE_ARRAY.
241 Abbv = new BitCodeAbbrev();
242 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
243 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
246 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
248 // Emit an entry count so the reader can reserve space.
249 TypeVals.push_back(TypeList.size());
250 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
253 // Loop over all of the types, emitting each in turn.
254 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
255 Type *T = TypeList[i];
259 switch (T->getTypeID()) {
260 default: llvm_unreachable("Unknown type!");
261 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
262 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
263 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
264 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
265 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
266 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
267 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
268 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
269 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
270 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
271 case Type::IntegerTyID:
273 Code = bitc::TYPE_CODE_INTEGER;
274 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
276 case Type::PointerTyID: {
277 PointerType *PTy = cast<PointerType>(T);
278 // POINTER: [pointee type, address space]
279 Code = bitc::TYPE_CODE_POINTER;
280 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
281 unsigned AddressSpace = PTy->getAddressSpace();
282 TypeVals.push_back(AddressSpace);
283 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
286 case Type::FunctionTyID: {
287 FunctionType *FT = cast<FunctionType>(T);
288 // FUNCTION: [isvararg, retty, paramty x N]
289 Code = bitc::TYPE_CODE_FUNCTION;
290 TypeVals.push_back(FT->isVarArg());
291 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
292 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
293 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
294 AbbrevToUse = FunctionAbbrev;
297 case Type::StructTyID: {
298 StructType *ST = cast<StructType>(T);
299 // STRUCT: [ispacked, eltty x N]
300 TypeVals.push_back(ST->isPacked());
301 // Output all of the element types.
302 for (StructType::element_iterator I = ST->element_begin(),
303 E = ST->element_end(); I != E; ++I)
304 TypeVals.push_back(VE.getTypeID(*I));
306 if (ST->isLiteral()) {
307 Code = bitc::TYPE_CODE_STRUCT_ANON;
308 AbbrevToUse = StructAnonAbbrev;
310 if (ST->isOpaque()) {
311 Code = bitc::TYPE_CODE_OPAQUE;
313 Code = bitc::TYPE_CODE_STRUCT_NAMED;
314 AbbrevToUse = StructNamedAbbrev;
317 // Emit the name if it is present.
318 if (!ST->getName().empty())
319 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
320 StructNameAbbrev, Stream);
324 case Type::ArrayTyID: {
325 ArrayType *AT = cast<ArrayType>(T);
326 // ARRAY: [numelts, eltty]
327 Code = bitc::TYPE_CODE_ARRAY;
328 TypeVals.push_back(AT->getNumElements());
329 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
330 AbbrevToUse = ArrayAbbrev;
333 case Type::VectorTyID: {
334 VectorType *VT = cast<VectorType>(T);
335 // VECTOR [numelts, eltty]
336 Code = bitc::TYPE_CODE_VECTOR;
337 TypeVals.push_back(VT->getNumElements());
338 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
343 // Emit the finished record.
344 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
351 static unsigned getEncodedLinkage(const GlobalValue *GV) {
352 switch (GV->getLinkage()) {
353 case GlobalValue::ExternalLinkage: return 0;
354 case GlobalValue::WeakAnyLinkage: return 1;
355 case GlobalValue::AppendingLinkage: return 2;
356 case GlobalValue::InternalLinkage: return 3;
357 case GlobalValue::LinkOnceAnyLinkage: return 4;
358 case GlobalValue::DLLImportLinkage: return 5;
359 case GlobalValue::DLLExportLinkage: return 6;
360 case GlobalValue::ExternalWeakLinkage: return 7;
361 case GlobalValue::CommonLinkage: return 8;
362 case GlobalValue::PrivateLinkage: return 9;
363 case GlobalValue::WeakODRLinkage: return 10;
364 case GlobalValue::LinkOnceODRLinkage: return 11;
365 case GlobalValue::AvailableExternallyLinkage: return 12;
366 case GlobalValue::LinkerPrivateLinkage: return 13;
367 case GlobalValue::LinkerPrivateWeakLinkage: return 14;
368 case GlobalValue::LinkerPrivateWeakDefAutoLinkage: return 15;
370 llvm_unreachable("Invalid linkage");
373 static unsigned getEncodedVisibility(const GlobalValue *GV) {
374 switch (GV->getVisibility()) {
375 case GlobalValue::DefaultVisibility: return 0;
376 case GlobalValue::HiddenVisibility: return 1;
377 case GlobalValue::ProtectedVisibility: return 2;
379 llvm_unreachable("Invalid visibility");
382 // Emit top-level description of module, including target triple, inline asm,
383 // descriptors for global variables, and function prototype info.
384 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
385 BitstreamWriter &Stream) {
386 // Emit the list of dependent libraries for the Module.
387 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
388 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
390 // Emit various pieces of data attached to a module.
391 if (!M->getTargetTriple().empty())
392 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
394 if (!M->getDataLayout().empty())
395 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
397 if (!M->getModuleInlineAsm().empty())
398 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
401 // Emit information about sections and GC, computing how many there are. Also
402 // compute the maximum alignment value.
403 std::map<std::string, unsigned> SectionMap;
404 std::map<std::string, unsigned> GCMap;
405 unsigned MaxAlignment = 0;
406 unsigned MaxGlobalType = 0;
407 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
409 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
410 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
411 if (GV->hasSection()) {
412 // Give section names unique ID's.
413 unsigned &Entry = SectionMap[GV->getSection()];
415 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
417 Entry = SectionMap.size();
421 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
422 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
423 if (F->hasSection()) {
424 // Give section names unique ID's.
425 unsigned &Entry = SectionMap[F->getSection()];
427 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
429 Entry = SectionMap.size();
433 // Same for GC names.
434 unsigned &Entry = GCMap[F->getGC()];
436 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
438 Entry = GCMap.size();
443 // Emit abbrev for globals, now that we know # sections and max alignment.
444 unsigned SimpleGVarAbbrev = 0;
445 if (!M->global_empty()) {
446 // Add an abbrev for common globals with no visibility or thread localness.
447 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
448 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
449 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
450 Log2_32_Ceil(MaxGlobalType+1)));
451 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
452 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
453 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
454 if (MaxAlignment == 0) // Alignment.
455 Abbv->Add(BitCodeAbbrevOp(0));
457 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
458 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
459 Log2_32_Ceil(MaxEncAlignment+1)));
461 if (SectionMap.empty()) // Section.
462 Abbv->Add(BitCodeAbbrevOp(0));
464 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
465 Log2_32_Ceil(SectionMap.size()+1)));
466 // Don't bother emitting vis + thread local.
467 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
470 // Emit the global variable information.
471 SmallVector<unsigned, 64> Vals;
472 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
474 unsigned AbbrevToUse = 0;
476 // GLOBALVAR: [type, isconst, initid,
477 // linkage, alignment, section, visibility, threadlocal,
479 Vals.push_back(VE.getTypeID(GV->getType()));
480 Vals.push_back(GV->isConstant());
481 Vals.push_back(GV->isDeclaration() ? 0 :
482 (VE.getValueID(GV->getInitializer()) + 1));
483 Vals.push_back(getEncodedLinkage(GV));
484 Vals.push_back(Log2_32(GV->getAlignment())+1);
485 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
486 if (GV->isThreadLocal() ||
487 GV->getVisibility() != GlobalValue::DefaultVisibility ||
488 GV->hasUnnamedAddr()) {
489 Vals.push_back(getEncodedVisibility(GV));
490 Vals.push_back(GV->isThreadLocal());
491 Vals.push_back(GV->hasUnnamedAddr());
493 AbbrevToUse = SimpleGVarAbbrev;
496 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
500 // Emit the function proto information.
501 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
502 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
503 // section, visibility, gc, unnamed_addr]
504 Vals.push_back(VE.getTypeID(F->getType()));
505 Vals.push_back(F->getCallingConv());
506 Vals.push_back(F->isDeclaration());
507 Vals.push_back(getEncodedLinkage(F));
508 Vals.push_back(VE.getAttributeID(F->getAttributes()));
509 Vals.push_back(Log2_32(F->getAlignment())+1);
510 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
511 Vals.push_back(getEncodedVisibility(F));
512 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
513 Vals.push_back(F->hasUnnamedAddr());
515 unsigned AbbrevToUse = 0;
516 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
520 // Emit the alias information.
521 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
523 // ALIAS: [alias type, aliasee val#, linkage, visibility]
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 EmitAPInt(SmallVectorImpl<uint64_t> &Vals,
715 unsigned &Code, unsigned &AbbrevToUse, const APInt &Val,
716 bool EmitSizeForWideNumbers = false
718 if (Val.getBitWidth() <= 64) {
719 uint64_t V = Val.getSExtValue();
721 Vals.push_back(V << 1);
723 Vals.push_back((-V << 1) | 1);
724 Code = bitc::CST_CODE_INTEGER;
725 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
727 // Wide integers, > 64 bits in size.
728 // We have an arbitrary precision integer value to write whose
729 // bit width is > 64. However, in canonical unsigned integer
730 // format it is likely that the high bits are going to be zero.
731 // So, we only write the number of active words.
732 unsigned NWords = Val.getActiveWords();
734 if (EmitSizeForWideNumbers)
735 Vals.push_back(NWords);
737 const uint64_t *RawWords = Val.getRawData();
738 for (unsigned i = 0; i != NWords; ++i) {
739 int64_t V = RawWords[i];
741 Vals.push_back(V << 1);
743 Vals.push_back((-V << 1) | 1);
745 Code = bitc::CST_CODE_WIDE_INTEGER;
749 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
750 const ValueEnumerator &VE,
751 BitstreamWriter &Stream, bool isGlobal) {
752 if (FirstVal == LastVal) return;
754 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
756 unsigned AggregateAbbrev = 0;
757 unsigned String8Abbrev = 0;
758 unsigned CString7Abbrev = 0;
759 unsigned CString6Abbrev = 0;
760 // If this is a constant pool for the module, emit module-specific abbrevs.
762 // Abbrev for CST_CODE_AGGREGATE.
763 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
764 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
765 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
766 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
767 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
769 // Abbrev for CST_CODE_STRING.
770 Abbv = new BitCodeAbbrev();
771 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
772 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
773 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
774 String8Abbrev = Stream.EmitAbbrev(Abbv);
775 // Abbrev for CST_CODE_CSTRING.
776 Abbv = new BitCodeAbbrev();
777 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
778 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
779 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
780 CString7Abbrev = Stream.EmitAbbrev(Abbv);
781 // Abbrev for CST_CODE_CSTRING.
782 Abbv = new BitCodeAbbrev();
783 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
784 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
785 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
786 CString6Abbrev = Stream.EmitAbbrev(Abbv);
789 SmallVector<uint64_t, 64> Record;
791 const ValueEnumerator::ValueList &Vals = VE.getValues();
793 for (unsigned i = FirstVal; i != LastVal; ++i) {
794 const Value *V = Vals[i].first;
795 // If we need to switch types, do so now.
796 if (V->getType() != LastTy) {
797 LastTy = V->getType();
798 Record.push_back(VE.getTypeID(LastTy));
799 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
800 CONSTANTS_SETTYPE_ABBREV);
804 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
805 Record.push_back(unsigned(IA->hasSideEffects()) |
806 unsigned(IA->isAlignStack()) << 1);
808 // Add the asm string.
809 const std::string &AsmStr = IA->getAsmString();
810 Record.push_back(AsmStr.size());
811 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
812 Record.push_back(AsmStr[i]);
814 // Add the constraint string.
815 const std::string &ConstraintStr = IA->getConstraintString();
816 Record.push_back(ConstraintStr.size());
817 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
818 Record.push_back(ConstraintStr[i]);
819 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
823 const Constant *C = cast<Constant>(V);
825 unsigned AbbrevToUse = 0;
826 if (C->isNullValue()) {
827 Code = bitc::CST_CODE_NULL;
828 } else if (isa<UndefValue>(C)) {
829 Code = bitc::CST_CODE_UNDEF;
830 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
831 EmitAPInt(Record, Code, AbbrevToUse, IV->getValue());
832 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
833 Code = bitc::CST_CODE_FLOAT;
834 Type *Ty = CFP->getType();
835 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
836 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
837 } else if (Ty->isX86_FP80Ty()) {
838 // api needed to prevent premature destruction
839 // bits are not in the same order as a normal i80 APInt, compensate.
840 APInt api = CFP->getValueAPF().bitcastToAPInt();
841 const uint64_t *p = api.getRawData();
842 Record.push_back((p[1] << 48) | (p[0] >> 16));
843 Record.push_back(p[0] & 0xffffLL);
844 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
845 APInt api = CFP->getValueAPF().bitcastToAPInt();
846 const uint64_t *p = api.getRawData();
847 Record.push_back(p[0]);
848 Record.push_back(p[1]);
850 assert (0 && "Unknown FP type!");
852 } else if (isa<ConstantDataSequential>(C) &&
853 cast<ConstantDataSequential>(C)->isString()) {
854 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
855 // Emit constant strings specially.
856 unsigned NumElts = Str->getNumElements();
857 // If this is a null-terminated string, use the denser CSTRING encoding.
858 if (Str->isCString()) {
859 Code = bitc::CST_CODE_CSTRING;
860 --NumElts; // Don't encode the null, which isn't allowed by char6.
862 Code = bitc::CST_CODE_STRING;
863 AbbrevToUse = String8Abbrev;
865 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
866 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
867 for (unsigned i = 0; i != NumElts; ++i) {
868 unsigned char V = Str->getElementAsInteger(i);
870 isCStr7 &= (V & 128) == 0;
872 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
876 AbbrevToUse = CString6Abbrev;
878 AbbrevToUse = CString7Abbrev;
879 } else if (const ConstantDataSequential *CDS =
880 dyn_cast<ConstantDataSequential>(C)) {
881 Code = bitc::CST_CODE_DATA;
882 Type *EltTy = CDS->getType()->getElementType();
883 if (isa<IntegerType>(EltTy)) {
884 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
885 Record.push_back(CDS->getElementAsInteger(i));
886 } else if (EltTy->isFloatTy()) {
887 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
888 union { float F; uint32_t I; };
889 F = CDS->getElementAsFloat(i);
893 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
894 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
895 union { double F; uint64_t I; };
896 F = CDS->getElementAsDouble(i);
900 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
901 isa<ConstantVector>(C)) {
902 Code = bitc::CST_CODE_AGGREGATE;
903 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
904 Record.push_back(VE.getValueID(C->getOperand(i)));
905 AbbrevToUse = AggregateAbbrev;
906 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
907 switch (CE->getOpcode()) {
909 if (Instruction::isCast(CE->getOpcode())) {
910 Code = bitc::CST_CODE_CE_CAST;
911 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
912 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
913 Record.push_back(VE.getValueID(C->getOperand(0)));
914 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
916 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
917 Code = bitc::CST_CODE_CE_BINOP;
918 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
919 Record.push_back(VE.getValueID(C->getOperand(0)));
920 Record.push_back(VE.getValueID(C->getOperand(1)));
921 uint64_t Flags = GetOptimizationFlags(CE);
923 Record.push_back(Flags);
926 case Instruction::GetElementPtr:
927 Code = bitc::CST_CODE_CE_GEP;
928 if (cast<GEPOperator>(C)->isInBounds())
929 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
930 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
931 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
932 Record.push_back(VE.getValueID(C->getOperand(i)));
935 case Instruction::Select:
936 Code = bitc::CST_CODE_CE_SELECT;
937 Record.push_back(VE.getValueID(C->getOperand(0)));
938 Record.push_back(VE.getValueID(C->getOperand(1)));
939 Record.push_back(VE.getValueID(C->getOperand(2)));
941 case Instruction::ExtractElement:
942 Code = bitc::CST_CODE_CE_EXTRACTELT;
943 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
944 Record.push_back(VE.getValueID(C->getOperand(0)));
945 Record.push_back(VE.getValueID(C->getOperand(1)));
947 case Instruction::InsertElement:
948 Code = bitc::CST_CODE_CE_INSERTELT;
949 Record.push_back(VE.getValueID(C->getOperand(0)));
950 Record.push_back(VE.getValueID(C->getOperand(1)));
951 Record.push_back(VE.getValueID(C->getOperand(2)));
953 case Instruction::ShuffleVector:
954 // If the return type and argument types are the same, this is a
955 // standard shufflevector instruction. If the types are different,
956 // then the shuffle is widening or truncating the input vectors, and
957 // the argument type must also be encoded.
958 if (C->getType() == C->getOperand(0)->getType()) {
959 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
961 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
962 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
964 Record.push_back(VE.getValueID(C->getOperand(0)));
965 Record.push_back(VE.getValueID(C->getOperand(1)));
966 Record.push_back(VE.getValueID(C->getOperand(2)));
968 case Instruction::ICmp:
969 case Instruction::FCmp:
970 Code = bitc::CST_CODE_CE_CMP;
971 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
972 Record.push_back(VE.getValueID(C->getOperand(0)));
973 Record.push_back(VE.getValueID(C->getOperand(1)));
974 Record.push_back(CE->getPredicate());
977 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
978 Code = bitc::CST_CODE_BLOCKADDRESS;
979 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
980 Record.push_back(VE.getValueID(BA->getFunction()));
981 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
986 llvm_unreachable("Unknown constant!");
988 Stream.EmitRecord(Code, Record, AbbrevToUse);
995 static void WriteModuleConstants(const ValueEnumerator &VE,
996 BitstreamWriter &Stream) {
997 const ValueEnumerator::ValueList &Vals = VE.getValues();
999 // Find the first constant to emit, which is the first non-globalvalue value.
1000 // We know globalvalues have been emitted by WriteModuleInfo.
1001 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1002 if (!isa<GlobalValue>(Vals[i].first)) {
1003 WriteConstants(i, Vals.size(), VE, Stream, true);
1009 /// PushValueAndType - The file has to encode both the value and type id for
1010 /// many values, because we need to know what type to create for forward
1011 /// references. However, most operands are not forward references, so this type
1012 /// field is not needed.
1014 /// This function adds V's value ID to Vals. If the value ID is higher than the
1015 /// instruction ID, then it is a forward reference, and it also includes the
1017 static bool PushValueAndType(const Value *V, unsigned InstID,
1018 SmallVector<unsigned, 64> &Vals,
1019 ValueEnumerator &VE) {
1020 unsigned ValID = VE.getValueID(V);
1021 Vals.push_back(ValID);
1022 if (ValID >= InstID) {
1023 Vals.push_back(VE.getTypeID(V->getType()));
1029 /// WriteInstruction - Emit an instruction to the specified stream.
1030 static void WriteInstruction(const Instruction &I, unsigned InstID,
1031 ValueEnumerator &VE, BitstreamWriter &Stream,
1032 SmallVector<unsigned, 64> &Vals) {
1034 unsigned AbbrevToUse = 0;
1035 VE.setInstructionID(&I);
1036 switch (I.getOpcode()) {
1038 if (Instruction::isCast(I.getOpcode())) {
1039 Code = bitc::FUNC_CODE_INST_CAST;
1040 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1041 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1042 Vals.push_back(VE.getTypeID(I.getType()));
1043 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1045 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1046 Code = bitc::FUNC_CODE_INST_BINOP;
1047 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1048 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1049 Vals.push_back(VE.getValueID(I.getOperand(1)));
1050 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1051 uint64_t Flags = GetOptimizationFlags(&I);
1053 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1054 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1055 Vals.push_back(Flags);
1060 case Instruction::GetElementPtr:
1061 Code = bitc::FUNC_CODE_INST_GEP;
1062 if (cast<GEPOperator>(&I)->isInBounds())
1063 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1064 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1065 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1067 case Instruction::ExtractValue: {
1068 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1069 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1070 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1071 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1075 case Instruction::InsertValue: {
1076 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1077 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1078 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1079 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1080 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1084 case Instruction::Select:
1085 Code = bitc::FUNC_CODE_INST_VSELECT;
1086 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1087 Vals.push_back(VE.getValueID(I.getOperand(2)));
1088 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1090 case Instruction::ExtractElement:
1091 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1092 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1093 Vals.push_back(VE.getValueID(I.getOperand(1)));
1095 case Instruction::InsertElement:
1096 Code = bitc::FUNC_CODE_INST_INSERTELT;
1097 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1098 Vals.push_back(VE.getValueID(I.getOperand(1)));
1099 Vals.push_back(VE.getValueID(I.getOperand(2)));
1101 case Instruction::ShuffleVector:
1102 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1103 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1104 Vals.push_back(VE.getValueID(I.getOperand(1)));
1105 Vals.push_back(VE.getValueID(I.getOperand(2)));
1107 case Instruction::ICmp:
1108 case Instruction::FCmp:
1109 // compare returning Int1Ty or vector of Int1Ty
1110 Code = bitc::FUNC_CODE_INST_CMP2;
1111 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1112 Vals.push_back(VE.getValueID(I.getOperand(1)));
1113 Vals.push_back(cast<CmpInst>(I).getPredicate());
1116 case Instruction::Ret:
1118 Code = bitc::FUNC_CODE_INST_RET;
1119 unsigned NumOperands = I.getNumOperands();
1120 if (NumOperands == 0)
1121 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1122 else if (NumOperands == 1) {
1123 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1124 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1126 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1127 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1131 case Instruction::Br:
1133 Code = bitc::FUNC_CODE_INST_BR;
1134 BranchInst &II = cast<BranchInst>(I);
1135 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1136 if (II.isConditional()) {
1137 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1138 Vals.push_back(VE.getValueID(II.getCondition()));
1142 case Instruction::Switch:
1144 // Redefine Vals, since here we need to use 64 bit values
1145 // explicitly to store large APInt numbers.
1146 SmallVector<uint64_t, 128> Vals64;
1148 Code = bitc::FUNC_CODE_INST_SWITCH;
1149 SwitchInst &SI = cast<SwitchInst>(I);
1151 uint32_t SwitchRecordHeader = SI.hash() | (SWITCH_INST_MAGIC << 16);
1152 Vals64.push_back(SwitchRecordHeader);
1154 Vals64.push_back(VE.getTypeID(SI.getCondition()->getType()));
1155 Vals64.push_back(VE.getValueID(SI.getCondition()));
1156 Vals64.push_back(VE.getValueID(SI.getDefaultDest()));
1157 Vals64.push_back(SI.getNumCases());
1158 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
1160 IntegersSubset CaseRanges = i.getCaseValueEx();
1161 Vals64.push_back(CaseRanges.getNumItems());
1162 for (unsigned ri = 0, rn = CaseRanges.getNumItems(); ri != rn; ++ri) {
1163 IntegersSubset::Range r = CaseRanges.getItem(ri);
1164 bool IsSingleNumber = r.isSingleNumber();
1166 Vals64.push_back(IsSingleNumber);
1168 unsigned Code, Abbrev; // will unused.
1170 EmitAPInt(Vals64, Code, Abbrev, r.getLow(), true);
1171 if (!IsSingleNumber)
1172 EmitAPInt(Vals64, Code, Abbrev, r.getHigh(), true);
1174 Vals64.push_back(VE.getValueID(i.getCaseSuccessor()));
1177 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1179 // Also do expected action - clear external Vals collection:
1184 case Instruction::IndirectBr:
1185 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1186 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1187 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1188 Vals.push_back(VE.getValueID(I.getOperand(i)));
1191 case Instruction::Invoke: {
1192 const InvokeInst *II = cast<InvokeInst>(&I);
1193 const Value *Callee(II->getCalledValue());
1194 PointerType *PTy = cast<PointerType>(Callee->getType());
1195 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1196 Code = bitc::FUNC_CODE_INST_INVOKE;
1198 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1199 Vals.push_back(II->getCallingConv());
1200 Vals.push_back(VE.getValueID(II->getNormalDest()));
1201 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1202 PushValueAndType(Callee, InstID, Vals, VE);
1204 // Emit value #'s for the fixed parameters.
1205 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1206 Vals.push_back(VE.getValueID(I.getOperand(i))); // fixed param.
1208 // Emit type/value pairs for varargs params.
1209 if (FTy->isVarArg()) {
1210 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1212 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1216 case Instruction::Resume:
1217 Code = bitc::FUNC_CODE_INST_RESUME;
1218 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1220 case Instruction::Unreachable:
1221 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1222 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1225 case Instruction::PHI: {
1226 const PHINode &PN = cast<PHINode>(I);
1227 Code = bitc::FUNC_CODE_INST_PHI;
1228 Vals.push_back(VE.getTypeID(PN.getType()));
1229 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1230 Vals.push_back(VE.getValueID(PN.getIncomingValue(i)));
1231 Vals.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1236 case Instruction::LandingPad: {
1237 const LandingPadInst &LP = cast<LandingPadInst>(I);
1238 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1239 Vals.push_back(VE.getTypeID(LP.getType()));
1240 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1241 Vals.push_back(LP.isCleanup());
1242 Vals.push_back(LP.getNumClauses());
1243 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1245 Vals.push_back(LandingPadInst::Catch);
1247 Vals.push_back(LandingPadInst::Filter);
1248 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1253 case Instruction::Alloca:
1254 Code = bitc::FUNC_CODE_INST_ALLOCA;
1255 Vals.push_back(VE.getTypeID(I.getType()));
1256 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1257 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1258 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1261 case Instruction::Load:
1262 if (cast<LoadInst>(I).isAtomic()) {
1263 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1264 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1266 Code = bitc::FUNC_CODE_INST_LOAD;
1267 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1268 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1270 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1271 Vals.push_back(cast<LoadInst>(I).isVolatile());
1272 if (cast<LoadInst>(I).isAtomic()) {
1273 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1274 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1277 case Instruction::Store:
1278 if (cast<StoreInst>(I).isAtomic())
1279 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1281 Code = bitc::FUNC_CODE_INST_STORE;
1282 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1283 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
1284 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1285 Vals.push_back(cast<StoreInst>(I).isVolatile());
1286 if (cast<StoreInst>(I).isAtomic()) {
1287 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1288 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1291 case Instruction::AtomicCmpXchg:
1292 Code = bitc::FUNC_CODE_INST_CMPXCHG;
1293 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1294 Vals.push_back(VE.getValueID(I.getOperand(1))); // cmp.
1295 Vals.push_back(VE.getValueID(I.getOperand(2))); // newval.
1296 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1297 Vals.push_back(GetEncodedOrdering(
1298 cast<AtomicCmpXchgInst>(I).getOrdering()));
1299 Vals.push_back(GetEncodedSynchScope(
1300 cast<AtomicCmpXchgInst>(I).getSynchScope()));
1302 case Instruction::AtomicRMW:
1303 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1304 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1305 Vals.push_back(VE.getValueID(I.getOperand(1))); // val.
1306 Vals.push_back(GetEncodedRMWOperation(
1307 cast<AtomicRMWInst>(I).getOperation()));
1308 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1309 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1310 Vals.push_back(GetEncodedSynchScope(
1311 cast<AtomicRMWInst>(I).getSynchScope()));
1313 case Instruction::Fence:
1314 Code = bitc::FUNC_CODE_INST_FENCE;
1315 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1316 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1318 case Instruction::Call: {
1319 const CallInst &CI = cast<CallInst>(I);
1320 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1321 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1323 Code = bitc::FUNC_CODE_INST_CALL;
1325 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1326 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1327 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1329 // Emit value #'s for the fixed parameters.
1330 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1331 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); // fixed param.
1333 // Emit type/value pairs for varargs params.
1334 if (FTy->isVarArg()) {
1335 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1337 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1341 case Instruction::VAArg:
1342 Code = bitc::FUNC_CODE_INST_VAARG;
1343 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1344 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
1345 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1349 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1353 // Emit names for globals/functions etc.
1354 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1355 const ValueEnumerator &VE,
1356 BitstreamWriter &Stream) {
1357 if (VST.empty()) return;
1358 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1360 // FIXME: Set up the abbrev, we know how many values there are!
1361 // FIXME: We know if the type names can use 7-bit ascii.
1362 SmallVector<unsigned, 64> NameVals;
1364 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1367 const ValueName &Name = *SI;
1369 // Figure out the encoding to use for the name.
1371 bool isChar6 = true;
1372 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1375 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1376 if ((unsigned char)*C & 128) {
1378 break; // don't bother scanning the rest.
1382 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1384 // VST_ENTRY: [valueid, namechar x N]
1385 // VST_BBENTRY: [bbid, namechar x N]
1387 if (isa<BasicBlock>(SI->getValue())) {
1388 Code = bitc::VST_CODE_BBENTRY;
1390 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1392 Code = bitc::VST_CODE_ENTRY;
1394 AbbrevToUse = VST_ENTRY_6_ABBREV;
1396 AbbrevToUse = VST_ENTRY_7_ABBREV;
1399 NameVals.push_back(VE.getValueID(SI->getValue()));
1400 for (const char *P = Name.getKeyData(),
1401 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1402 NameVals.push_back((unsigned char)*P);
1404 // Emit the finished record.
1405 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1411 /// WriteFunction - Emit a function body to the module stream.
1412 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1413 BitstreamWriter &Stream) {
1414 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1415 VE.incorporateFunction(F);
1417 SmallVector<unsigned, 64> Vals;
1419 // Emit the number of basic blocks, so the reader can create them ahead of
1421 Vals.push_back(VE.getBasicBlocks().size());
1422 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1425 // If there are function-local constants, emit them now.
1426 unsigned CstStart, CstEnd;
1427 VE.getFunctionConstantRange(CstStart, CstEnd);
1428 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1430 // If there is function-local metadata, emit it now.
1431 WriteFunctionLocalMetadata(F, VE, Stream);
1433 // Keep a running idea of what the instruction ID is.
1434 unsigned InstID = CstEnd;
1436 bool NeedsMetadataAttachment = false;
1440 // Finally, emit all the instructions, in order.
1441 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1442 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1444 WriteInstruction(*I, InstID, VE, Stream, Vals);
1446 if (!I->getType()->isVoidTy())
1449 // If the instruction has metadata, write a metadata attachment later.
1450 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1452 // If the instruction has a debug location, emit it.
1453 DebugLoc DL = I->getDebugLoc();
1454 if (DL.isUnknown()) {
1456 } else if (DL == LastDL) {
1457 // Just repeat the same debug loc as last time.
1458 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1461 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1463 Vals.push_back(DL.getLine());
1464 Vals.push_back(DL.getCol());
1465 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1466 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1467 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1474 // Emit names for all the instructions etc.
1475 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1477 if (NeedsMetadataAttachment)
1478 WriteMetadataAttachment(F, VE, Stream);
1483 // Emit blockinfo, which defines the standard abbreviations etc.
1484 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1485 // We only want to emit block info records for blocks that have multiple
1486 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
1487 // blocks can defined their abbrevs inline.
1488 Stream.EnterBlockInfoBlock(2);
1490 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1491 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1492 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1493 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1494 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1495 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1496 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1497 Abbv) != VST_ENTRY_8_ABBREV)
1498 llvm_unreachable("Unexpected abbrev ordering!");
1501 { // 7-bit fixed width VST_ENTRY strings.
1502 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1503 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1504 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1505 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1506 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1507 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1508 Abbv) != VST_ENTRY_7_ABBREV)
1509 llvm_unreachable("Unexpected abbrev ordering!");
1511 { // 6-bit char6 VST_ENTRY strings.
1512 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1513 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1514 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1515 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1516 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1517 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1518 Abbv) != VST_ENTRY_6_ABBREV)
1519 llvm_unreachable("Unexpected abbrev ordering!");
1521 { // 6-bit char6 VST_BBENTRY strings.
1522 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1523 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1524 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1525 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1526 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1527 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1528 Abbv) != VST_BBENTRY_6_ABBREV)
1529 llvm_unreachable("Unexpected abbrev ordering!");
1534 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1535 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1536 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1537 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1538 Log2_32_Ceil(VE.getTypes().size()+1)));
1539 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1540 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1541 llvm_unreachable("Unexpected abbrev ordering!");
1544 { // INTEGER abbrev for CONSTANTS_BLOCK.
1545 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1546 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1547 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1548 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1549 Abbv) != CONSTANTS_INTEGER_ABBREV)
1550 llvm_unreachable("Unexpected abbrev ordering!");
1553 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1554 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1555 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1556 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1557 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1558 Log2_32_Ceil(VE.getTypes().size()+1)));
1559 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1561 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1562 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1563 llvm_unreachable("Unexpected abbrev ordering!");
1565 { // NULL abbrev for CONSTANTS_BLOCK.
1566 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1567 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1568 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1569 Abbv) != CONSTANTS_NULL_Abbrev)
1570 llvm_unreachable("Unexpected abbrev ordering!");
1573 // FIXME: This should only use space for first class types!
1575 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1576 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1577 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1578 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1579 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1580 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1581 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1582 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1583 llvm_unreachable("Unexpected abbrev ordering!");
1585 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1586 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1587 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1588 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1589 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1590 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1591 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1592 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1593 llvm_unreachable("Unexpected abbrev ordering!");
1595 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1596 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1597 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1598 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1599 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1600 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1601 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1602 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1603 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1604 llvm_unreachable("Unexpected abbrev ordering!");
1606 { // INST_CAST abbrev for FUNCTION_BLOCK.
1607 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1608 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1609 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1610 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1611 Log2_32_Ceil(VE.getTypes().size()+1)));
1612 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1613 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1614 Abbv) != FUNCTION_INST_CAST_ABBREV)
1615 llvm_unreachable("Unexpected abbrev ordering!");
1618 { // INST_RET abbrev for FUNCTION_BLOCK.
1619 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1620 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1621 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1622 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1623 llvm_unreachable("Unexpected abbrev ordering!");
1625 { // INST_RET abbrev for FUNCTION_BLOCK.
1626 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1627 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1628 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1629 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1630 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1631 llvm_unreachable("Unexpected abbrev ordering!");
1633 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1634 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1635 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1636 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1637 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1638 llvm_unreachable("Unexpected abbrev ordering!");
1644 // Sort the Users based on the order in which the reader parses the bitcode
1646 static bool bitcodereader_order(const User *lhs, const User *rhs) {
1651 static void WriteUseList(const Value *V, const ValueEnumerator &VE,
1652 BitstreamWriter &Stream) {
1654 // One or zero uses can't get out of order.
1655 if (V->use_empty() || V->hasNUses(1))
1658 // Make a copy of the in-memory use-list for sorting.
1659 unsigned UseListSize = std::distance(V->use_begin(), V->use_end());
1660 SmallVector<const User*, 8> UseList;
1661 UseList.reserve(UseListSize);
1662 for (Value::const_use_iterator I = V->use_begin(), E = V->use_end();
1665 UseList.push_back(U);
1668 // Sort the copy based on the order read by the BitcodeReader.
1669 std::sort(UseList.begin(), UseList.end(), bitcodereader_order);
1671 // TODO: Generate a diff between the BitcodeWriter in-memory use-list and the
1672 // sorted list (i.e., the expected BitcodeReader in-memory use-list).
1674 // TODO: Emit the USELIST_CODE_ENTRYs.
1677 static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE,
1678 BitstreamWriter &Stream) {
1679 VE.incorporateFunction(*F);
1681 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1683 WriteUseList(AI, VE, Stream);
1684 for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE;
1686 WriteUseList(BB, VE, Stream);
1687 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
1689 WriteUseList(II, VE, Stream);
1690 for (User::const_op_iterator OI = II->op_begin(), E = II->op_end();
1692 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
1693 isa<InlineAsm>(*OI))
1694 WriteUseList(*OI, VE, Stream);
1702 static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE,
1703 BitstreamWriter &Stream) {
1704 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
1706 // XXX: this modifies the module, but in a way that should never change the
1707 // behavior of any pass or codegen in LLVM. The problem is that GVs may
1708 // contain entries in the use_list that do not exist in the Module and are
1709 // not stored in the .bc file.
1710 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1712 I->removeDeadConstantUsers();
1714 // Write the global variables.
1715 for (Module::const_global_iterator GI = M->global_begin(),
1716 GE = M->global_end(); GI != GE; ++GI) {
1717 WriteUseList(GI, VE, Stream);
1719 // Write the global variable initializers.
1720 if (GI->hasInitializer())
1721 WriteUseList(GI->getInitializer(), VE, Stream);
1724 // Write the functions.
1725 for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
1726 WriteUseList(FI, VE, Stream);
1727 if (!FI->isDeclaration())
1728 WriteFunctionUseList(FI, VE, Stream);
1731 // Write the aliases.
1732 for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end();
1734 WriteUseList(AI, VE, Stream);
1735 WriteUseList(AI->getAliasee(), VE, Stream);
1741 /// WriteModule - Emit the specified module to the bitstream.
1742 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1743 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1745 // Emit the version number if it is non-zero.
1747 SmallVector<unsigned, 1> Vals;
1748 Vals.push_back(CurVersion);
1749 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1752 // Analyze the module, enumerating globals, functions, etc.
1753 ValueEnumerator VE(M);
1755 // Emit blockinfo, which defines the standard abbreviations etc.
1756 WriteBlockInfo(VE, Stream);
1758 // Emit information about parameter attributes.
1759 WriteAttributeTable(VE, Stream);
1761 // Emit information describing all of the types in the module.
1762 WriteTypeTable(VE, Stream);
1764 // Emit top-level description of module, including target triple, inline asm,
1765 // descriptors for global variables, and function prototype info.
1766 WriteModuleInfo(M, VE, Stream);
1769 WriteModuleConstants(VE, Stream);
1772 WriteModuleMetadata(M, VE, Stream);
1775 WriteModuleMetadataStore(M, Stream);
1777 // Emit names for globals/functions etc.
1778 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1781 if (EnablePreserveUseListOrdering)
1782 WriteModuleUseLists(M, VE, Stream);
1784 // Emit function bodies.
1785 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1786 if (!F->isDeclaration())
1787 WriteFunction(*F, VE, Stream);
1792 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1793 /// header and trailer to make it compatible with the system archiver. To do
1794 /// this we emit the following header, and then emit a trailer that pads the
1795 /// file out to be a multiple of 16 bytes.
1797 /// struct bc_header {
1798 /// uint32_t Magic; // 0x0B17C0DE
1799 /// uint32_t Version; // Version, currently always 0.
1800 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1801 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1802 /// uint32_t CPUType; // CPU specifier.
1803 /// ... potentially more later ...
1806 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1807 DarwinBCHeaderSize = 5*4
1810 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
1811 uint32_t &Position) {
1812 Buffer[Position + 0] = (unsigned char) (Value >> 0);
1813 Buffer[Position + 1] = (unsigned char) (Value >> 8);
1814 Buffer[Position + 2] = (unsigned char) (Value >> 16);
1815 Buffer[Position + 3] = (unsigned char) (Value >> 24);
1819 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
1821 unsigned CPUType = ~0U;
1823 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1824 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1825 // number from /usr/include/mach/machine.h. It is ok to reproduce the
1826 // specific constants here because they are implicitly part of the Darwin ABI.
1828 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1829 DARWIN_CPU_TYPE_X86 = 7,
1830 DARWIN_CPU_TYPE_ARM = 12,
1831 DARWIN_CPU_TYPE_POWERPC = 18
1834 Triple::ArchType Arch = TT.getArch();
1835 if (Arch == Triple::x86_64)
1836 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1837 else if (Arch == Triple::x86)
1838 CPUType = DARWIN_CPU_TYPE_X86;
1839 else if (Arch == Triple::ppc)
1840 CPUType = DARWIN_CPU_TYPE_POWERPC;
1841 else if (Arch == Triple::ppc64)
1842 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1843 else if (Arch == Triple::arm || Arch == Triple::thumb)
1844 CPUType = DARWIN_CPU_TYPE_ARM;
1846 // Traditional Bitcode starts after header.
1847 assert(Buffer.size() >= DarwinBCHeaderSize &&
1848 "Expected header size to be reserved");
1849 unsigned BCOffset = DarwinBCHeaderSize;
1850 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
1852 // Write the magic and version.
1853 unsigned Position = 0;
1854 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
1855 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
1856 WriteInt32ToBuffer(BCOffset , Buffer, Position);
1857 WriteInt32ToBuffer(BCSize , Buffer, Position);
1858 WriteInt32ToBuffer(CPUType , Buffer, Position);
1860 // If the file is not a multiple of 16 bytes, insert dummy padding.
1861 while (Buffer.size() & 15)
1862 Buffer.push_back(0);
1865 /// WriteBitcodeToFile - Write the specified module to the specified output
1867 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1868 SmallVector<char, 1024> Buffer;
1869 Buffer.reserve(256*1024);
1871 // If this is darwin or another generic macho target, reserve space for the
1873 Triple TT(M->getTargetTriple());
1874 if (TT.isOSDarwin())
1875 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
1877 // Emit the module into the buffer.
1879 BitstreamWriter Stream(Buffer);
1881 // Emit the file header.
1882 Stream.Emit((unsigned)'B', 8);
1883 Stream.Emit((unsigned)'C', 8);
1884 Stream.Emit(0x0, 4);
1885 Stream.Emit(0xC, 4);
1886 Stream.Emit(0xE, 4);
1887 Stream.Emit(0xD, 4);
1890 WriteModule(M, Stream);
1893 if (TT.isOSDarwin())
1894 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
1896 // Write the generated bitstream to "Out".
1897 Out.write((char*)&Buffer.front(), Buffer.size());