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.
44 // VALUE_SYMTAB_BLOCK abbrev id's.
45 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
50 // CONSTANTS_BLOCK abbrev id's.
51 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
52 CONSTANTS_INTEGER_ABBREV,
53 CONSTANTS_CE_CAST_Abbrev,
54 CONSTANTS_NULL_Abbrev,
56 // FUNCTION_BLOCK abbrev id's.
57 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
58 FUNCTION_INST_BINOP_ABBREV,
59 FUNCTION_INST_BINOP_FLAGS_ABBREV,
60 FUNCTION_INST_CAST_ABBREV,
61 FUNCTION_INST_RET_VOID_ABBREV,
62 FUNCTION_INST_RET_VAL_ABBREV,
63 FUNCTION_INST_UNREACHABLE_ABBREV,
66 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
69 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
71 default: llvm_unreachable("Unknown cast instruction!");
72 case Instruction::Trunc : return bitc::CAST_TRUNC;
73 case Instruction::ZExt : return bitc::CAST_ZEXT;
74 case Instruction::SExt : return bitc::CAST_SEXT;
75 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
76 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
77 case Instruction::UIToFP : return bitc::CAST_UITOFP;
78 case Instruction::SIToFP : return bitc::CAST_SITOFP;
79 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
80 case Instruction::FPExt : return bitc::CAST_FPEXT;
81 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
82 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
83 case Instruction::BitCast : return bitc::CAST_BITCAST;
87 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
89 default: llvm_unreachable("Unknown binary instruction!");
90 case Instruction::Add:
91 case Instruction::FAdd: return bitc::BINOP_ADD;
92 case Instruction::Sub:
93 case Instruction::FSub: return bitc::BINOP_SUB;
94 case Instruction::Mul:
95 case Instruction::FMul: return bitc::BINOP_MUL;
96 case Instruction::UDiv: return bitc::BINOP_UDIV;
97 case Instruction::FDiv:
98 case Instruction::SDiv: return bitc::BINOP_SDIV;
99 case Instruction::URem: return bitc::BINOP_UREM;
100 case Instruction::FRem:
101 case Instruction::SRem: return bitc::BINOP_SREM;
102 case Instruction::Shl: return bitc::BINOP_SHL;
103 case Instruction::LShr: return bitc::BINOP_LSHR;
104 case Instruction::AShr: return bitc::BINOP_ASHR;
105 case Instruction::And: return bitc::BINOP_AND;
106 case Instruction::Or: return bitc::BINOP_OR;
107 case Instruction::Xor: return bitc::BINOP_XOR;
111 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
113 default: llvm_unreachable("Unknown RMW operation!");
114 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
115 case AtomicRMWInst::Add: return bitc::RMW_ADD;
116 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
117 case AtomicRMWInst::And: return bitc::RMW_AND;
118 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
119 case AtomicRMWInst::Or: return bitc::RMW_OR;
120 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
121 case AtomicRMWInst::Max: return bitc::RMW_MAX;
122 case AtomicRMWInst::Min: return bitc::RMW_MIN;
123 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
124 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
128 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
130 case NotAtomic: return bitc::ORDERING_NOTATOMIC;
131 case Unordered: return bitc::ORDERING_UNORDERED;
132 case Monotonic: return bitc::ORDERING_MONOTONIC;
133 case Acquire: return bitc::ORDERING_ACQUIRE;
134 case Release: return bitc::ORDERING_RELEASE;
135 case AcquireRelease: return bitc::ORDERING_ACQREL;
136 case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
138 llvm_unreachable("Invalid ordering");
141 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
142 switch (SynchScope) {
143 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
144 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
146 llvm_unreachable("Invalid synch scope");
149 static void WriteStringRecord(unsigned Code, StringRef Str,
150 unsigned AbbrevToUse, BitstreamWriter &Stream) {
151 SmallVector<unsigned, 64> Vals;
153 // Code: [strchar x N]
154 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
155 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
157 Vals.push_back(Str[i]);
160 // Emit the finished record.
161 Stream.EmitRecord(Code, Vals, AbbrevToUse);
164 // Emit information about parameter attributes.
165 static void WriteAttributeTable(const ValueEnumerator &VE,
166 BitstreamWriter &Stream) {
167 const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
168 if (Attrs.empty()) return;
170 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
172 SmallVector<uint64_t, 64> Record;
173 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
174 const AttrListPtr &A = Attrs[i];
175 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
176 const AttributeWithIndex &PAWI = A.getSlot(i);
177 Record.push_back(PAWI.Index);
178 Record.push_back(Attributes::encodeLLVMAttributesForBitcode(PAWI.Attrs));
181 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
188 /// WriteTypeTable - Write out the type table for a module.
189 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
190 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
192 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
193 SmallVector<uint64_t, 64> TypeVals;
195 uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
197 // Abbrev for TYPE_CODE_POINTER.
198 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
199 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
200 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
201 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
202 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
204 // Abbrev for TYPE_CODE_FUNCTION.
205 Abbv = new BitCodeAbbrev();
206 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
207 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
208 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
209 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
211 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
213 // Abbrev for TYPE_CODE_STRUCT_ANON.
214 Abbv = new BitCodeAbbrev();
215 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
216 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
217 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
218 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
220 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
222 // Abbrev for TYPE_CODE_STRUCT_NAME.
223 Abbv = new BitCodeAbbrev();
224 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
225 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
226 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
227 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
229 // Abbrev for TYPE_CODE_STRUCT_NAMED.
230 Abbv = new BitCodeAbbrev();
231 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
236 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
238 // Abbrev for TYPE_CODE_ARRAY.
239 Abbv = new BitCodeAbbrev();
240 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
241 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
242 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
244 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
246 // Emit an entry count so the reader can reserve space.
247 TypeVals.push_back(TypeList.size());
248 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
251 // Loop over all of the types, emitting each in turn.
252 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
253 Type *T = TypeList[i];
257 switch (T->getTypeID()) {
258 default: llvm_unreachable("Unknown type!");
259 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
260 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
261 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
262 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
263 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
264 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
265 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
266 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
267 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
268 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
269 case Type::IntegerTyID:
271 Code = bitc::TYPE_CODE_INTEGER;
272 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
274 case Type::PointerTyID: {
275 PointerType *PTy = cast<PointerType>(T);
276 // POINTER: [pointee type, address space]
277 Code = bitc::TYPE_CODE_POINTER;
278 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
279 unsigned AddressSpace = PTy->getAddressSpace();
280 TypeVals.push_back(AddressSpace);
281 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
284 case Type::FunctionTyID: {
285 FunctionType *FT = cast<FunctionType>(T);
286 // FUNCTION: [isvararg, retty, paramty x N]
287 Code = bitc::TYPE_CODE_FUNCTION;
288 TypeVals.push_back(FT->isVarArg());
289 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
290 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
291 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
292 AbbrevToUse = FunctionAbbrev;
295 case Type::StructTyID: {
296 StructType *ST = cast<StructType>(T);
297 // STRUCT: [ispacked, eltty x N]
298 TypeVals.push_back(ST->isPacked());
299 // Output all of the element types.
300 for (StructType::element_iterator I = ST->element_begin(),
301 E = ST->element_end(); I != E; ++I)
302 TypeVals.push_back(VE.getTypeID(*I));
304 if (ST->isLiteral()) {
305 Code = bitc::TYPE_CODE_STRUCT_ANON;
306 AbbrevToUse = StructAnonAbbrev;
308 if (ST->isOpaque()) {
309 Code = bitc::TYPE_CODE_OPAQUE;
311 Code = bitc::TYPE_CODE_STRUCT_NAMED;
312 AbbrevToUse = StructNamedAbbrev;
315 // Emit the name if it is present.
316 if (!ST->getName().empty())
317 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
318 StructNameAbbrev, Stream);
322 case Type::ArrayTyID: {
323 ArrayType *AT = cast<ArrayType>(T);
324 // ARRAY: [numelts, eltty]
325 Code = bitc::TYPE_CODE_ARRAY;
326 TypeVals.push_back(AT->getNumElements());
327 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
328 AbbrevToUse = ArrayAbbrev;
331 case Type::VectorTyID: {
332 VectorType *VT = cast<VectorType>(T);
333 // VECTOR [numelts, eltty]
334 Code = bitc::TYPE_CODE_VECTOR;
335 TypeVals.push_back(VT->getNumElements());
336 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
341 // Emit the finished record.
342 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
349 static unsigned getEncodedLinkage(const GlobalValue *GV) {
350 switch (GV->getLinkage()) {
351 case GlobalValue::ExternalLinkage: return 0;
352 case GlobalValue::WeakAnyLinkage: return 1;
353 case GlobalValue::AppendingLinkage: return 2;
354 case GlobalValue::InternalLinkage: return 3;
355 case GlobalValue::LinkOnceAnyLinkage: return 4;
356 case GlobalValue::DLLImportLinkage: return 5;
357 case GlobalValue::DLLExportLinkage: return 6;
358 case GlobalValue::ExternalWeakLinkage: return 7;
359 case GlobalValue::CommonLinkage: return 8;
360 case GlobalValue::PrivateLinkage: return 9;
361 case GlobalValue::WeakODRLinkage: return 10;
362 case GlobalValue::LinkOnceODRLinkage: return 11;
363 case GlobalValue::AvailableExternallyLinkage: return 12;
364 case GlobalValue::LinkerPrivateLinkage: return 13;
365 case GlobalValue::LinkerPrivateWeakLinkage: return 14;
366 case GlobalValue::LinkOnceODRAutoHideLinkage: return 15;
368 llvm_unreachable("Invalid linkage");
371 static unsigned getEncodedVisibility(const GlobalValue *GV) {
372 switch (GV->getVisibility()) {
373 case GlobalValue::DefaultVisibility: return 0;
374 case GlobalValue::HiddenVisibility: return 1;
375 case GlobalValue::ProtectedVisibility: return 2;
377 llvm_unreachable("Invalid visibility");
380 static unsigned getEncodedThreadLocalMode(const GlobalVariable *GV) {
381 switch (GV->getThreadLocalMode()) {
382 case GlobalVariable::NotThreadLocal: return 0;
383 case GlobalVariable::GeneralDynamicTLSModel: return 1;
384 case GlobalVariable::LocalDynamicTLSModel: return 2;
385 case GlobalVariable::InitialExecTLSModel: return 3;
386 case GlobalVariable::LocalExecTLSModel: return 4;
388 llvm_unreachable("Invalid TLS model");
391 // Emit top-level description of module, including target triple, inline asm,
392 // descriptors for global variables, and function prototype info.
393 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
394 BitstreamWriter &Stream) {
395 // Emit the list of dependent libraries for the Module.
396 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
397 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
399 // Emit various pieces of data attached to a module.
400 if (!M->getTargetTriple().empty())
401 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
403 if (!M->getDataLayout().empty())
404 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
406 if (!M->getModuleInlineAsm().empty())
407 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
410 // Emit information about sections and GC, computing how many there are. Also
411 // compute the maximum alignment value.
412 std::map<std::string, unsigned> SectionMap;
413 std::map<std::string, unsigned> GCMap;
414 unsigned MaxAlignment = 0;
415 unsigned MaxGlobalType = 0;
416 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
418 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
419 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
420 if (GV->hasSection()) {
421 // Give section names unique ID's.
422 unsigned &Entry = SectionMap[GV->getSection()];
424 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
426 Entry = SectionMap.size();
430 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
431 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
432 if (F->hasSection()) {
433 // Give section names unique ID's.
434 unsigned &Entry = SectionMap[F->getSection()];
436 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
438 Entry = SectionMap.size();
442 // Same for GC names.
443 unsigned &Entry = GCMap[F->getGC()];
445 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
447 Entry = GCMap.size();
452 // Emit abbrev for globals, now that we know # sections and max alignment.
453 unsigned SimpleGVarAbbrev = 0;
454 if (!M->global_empty()) {
455 // Add an abbrev for common globals with no visibility or thread localness.
456 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
457 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
458 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
459 Log2_32_Ceil(MaxGlobalType+1)));
460 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
461 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
462 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
463 if (MaxAlignment == 0) // Alignment.
464 Abbv->Add(BitCodeAbbrevOp(0));
466 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
467 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
468 Log2_32_Ceil(MaxEncAlignment+1)));
470 if (SectionMap.empty()) // Section.
471 Abbv->Add(BitCodeAbbrevOp(0));
473 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
474 Log2_32_Ceil(SectionMap.size()+1)));
475 // Don't bother emitting vis + thread local.
476 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
479 // Emit the global variable information.
480 SmallVector<unsigned, 64> Vals;
481 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
483 unsigned AbbrevToUse = 0;
485 // GLOBALVAR: [type, isconst, initid,
486 // linkage, alignment, section, visibility, threadlocal,
488 Vals.push_back(VE.getTypeID(GV->getType()));
489 Vals.push_back(GV->isConstant());
490 Vals.push_back(GV->isDeclaration() ? 0 :
491 (VE.getValueID(GV->getInitializer()) + 1));
492 Vals.push_back(getEncodedLinkage(GV));
493 Vals.push_back(Log2_32(GV->getAlignment())+1);
494 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
495 if (GV->isThreadLocal() ||
496 GV->getVisibility() != GlobalValue::DefaultVisibility ||
497 GV->hasUnnamedAddr()) {
498 Vals.push_back(getEncodedVisibility(GV));
499 Vals.push_back(getEncodedThreadLocalMode(GV));
500 Vals.push_back(GV->hasUnnamedAddr());
502 AbbrevToUse = SimpleGVarAbbrev;
505 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
509 // Emit the function proto information.
510 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
511 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
512 // section, visibility, gc, unnamed_addr]
513 Vals.push_back(VE.getTypeID(F->getType()));
514 Vals.push_back(F->getCallingConv());
515 Vals.push_back(F->isDeclaration());
516 Vals.push_back(getEncodedLinkage(F));
517 Vals.push_back(VE.getAttributeID(F->getAttributes()));
518 Vals.push_back(Log2_32(F->getAlignment())+1);
519 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
520 Vals.push_back(getEncodedVisibility(F));
521 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
522 Vals.push_back(F->hasUnnamedAddr());
524 unsigned AbbrevToUse = 0;
525 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
529 // Emit the alias information.
530 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
532 // ALIAS: [alias type, aliasee val#, linkage, visibility]
533 Vals.push_back(VE.getTypeID(AI->getType()));
534 Vals.push_back(VE.getValueID(AI->getAliasee()));
535 Vals.push_back(getEncodedLinkage(AI));
536 Vals.push_back(getEncodedVisibility(AI));
537 unsigned AbbrevToUse = 0;
538 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
543 static uint64_t GetOptimizationFlags(const Value *V) {
546 if (const OverflowingBinaryOperator *OBO =
547 dyn_cast<OverflowingBinaryOperator>(V)) {
548 if (OBO->hasNoSignedWrap())
549 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
550 if (OBO->hasNoUnsignedWrap())
551 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
552 } else if (const PossiblyExactOperator *PEO =
553 dyn_cast<PossiblyExactOperator>(V)) {
555 Flags |= 1 << bitc::PEO_EXACT;
556 } else if (const FPMathOperator *FPMO =
557 dyn_cast<const FPMathOperator>(V)) {
558 if (FPMO->hasUnsafeAlgebra())
559 Flags |= 1 << bitc::FMF_UNSAFE_ALGEBRA;
560 if (FPMO->hasNoNaNs())
561 Flags |= 1 << bitc::FMF_NO_NANS;
562 if (FPMO->hasNoInfs())
563 Flags |= 1 << bitc::FMF_NO_INFS;
564 if (FPMO->hasNoSignedZeros())
565 Flags |= 1 << bitc::FMF_NO_SIGNED_ZEROS;
566 if (FPMO->hasAllowReciprocal())
567 Flags |= 1 << bitc::FMF_ALLOW_RECIPROCAL;
573 static void WriteMDNode(const MDNode *N,
574 const ValueEnumerator &VE,
575 BitstreamWriter &Stream,
576 SmallVector<uint64_t, 64> &Record) {
577 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
578 if (N->getOperand(i)) {
579 Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
580 Record.push_back(VE.getValueID(N->getOperand(i)));
582 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
586 unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
588 Stream.EmitRecord(MDCode, Record, 0);
592 static void WriteModuleMetadata(const Module *M,
593 const ValueEnumerator &VE,
594 BitstreamWriter &Stream) {
595 const ValueEnumerator::ValueList &Vals = VE.getMDValues();
596 bool StartedMetadataBlock = false;
597 unsigned MDSAbbrev = 0;
598 SmallVector<uint64_t, 64> Record;
599 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
601 if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
602 if (!N->isFunctionLocal() || !N->getFunction()) {
603 if (!StartedMetadataBlock) {
604 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
605 StartedMetadataBlock = true;
607 WriteMDNode(N, VE, Stream, Record);
609 } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
610 if (!StartedMetadataBlock) {
611 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
613 // Abbrev for METADATA_STRING.
614 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
615 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
616 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
617 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
618 MDSAbbrev = Stream.EmitAbbrev(Abbv);
619 StartedMetadataBlock = true;
622 // Code: [strchar x N]
623 Record.append(MDS->begin(), MDS->end());
625 // Emit the finished record.
626 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
631 // Write named metadata.
632 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
633 E = M->named_metadata_end(); I != E; ++I) {
634 const NamedMDNode *NMD = I;
635 if (!StartedMetadataBlock) {
636 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
637 StartedMetadataBlock = true;
641 StringRef Str = NMD->getName();
642 for (unsigned i = 0, e = Str.size(); i != e; ++i)
643 Record.push_back(Str[i]);
644 Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
647 // Write named metadata operands.
648 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
649 Record.push_back(VE.getValueID(NMD->getOperand(i)));
650 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
654 if (StartedMetadataBlock)
658 static void WriteFunctionLocalMetadata(const Function &F,
659 const ValueEnumerator &VE,
660 BitstreamWriter &Stream) {
661 bool StartedMetadataBlock = false;
662 SmallVector<uint64_t, 64> Record;
663 const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues();
664 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
665 if (const MDNode *N = Vals[i])
666 if (N->isFunctionLocal() && N->getFunction() == &F) {
667 if (!StartedMetadataBlock) {
668 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
669 StartedMetadataBlock = true;
671 WriteMDNode(N, VE, Stream, Record);
674 if (StartedMetadataBlock)
678 static void WriteMetadataAttachment(const Function &F,
679 const ValueEnumerator &VE,
680 BitstreamWriter &Stream) {
681 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
683 SmallVector<uint64_t, 64> Record;
685 // Write metadata attachments
686 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
687 SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
689 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
690 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
693 I->getAllMetadataOtherThanDebugLoc(MDs);
695 // If no metadata, ignore instruction.
696 if (MDs.empty()) continue;
698 Record.push_back(VE.getInstructionID(I));
700 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
701 Record.push_back(MDs[i].first);
702 Record.push_back(VE.getValueID(MDs[i].second));
704 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
711 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
712 SmallVector<uint64_t, 64> Record;
714 // Write metadata kinds
715 // METADATA_KIND - [n x [id, name]]
716 SmallVector<StringRef, 4> Names;
717 M->getMDKindNames(Names);
719 if (Names.empty()) return;
721 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
723 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
724 Record.push_back(MDKindID);
725 StringRef KName = Names[MDKindID];
726 Record.append(KName.begin(), KName.end());
728 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
735 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
737 Vals.push_back(V << 1);
739 Vals.push_back((-V << 1) | 1);
742 static void EmitAPInt(SmallVectorImpl<uint64_t> &Vals,
743 unsigned &Code, unsigned &AbbrevToUse, const APInt &Val,
744 bool EmitSizeForWideNumbers = false
746 if (Val.getBitWidth() <= 64) {
747 uint64_t V = Val.getSExtValue();
748 emitSignedInt64(Vals, V);
749 Code = bitc::CST_CODE_INTEGER;
750 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
752 // Wide integers, > 64 bits in size.
753 // We have an arbitrary precision integer value to write whose
754 // bit width is > 64. However, in canonical unsigned integer
755 // format it is likely that the high bits are going to be zero.
756 // So, we only write the number of active words.
757 unsigned NWords = Val.getActiveWords();
759 if (EmitSizeForWideNumbers)
760 Vals.push_back(NWords);
762 const uint64_t *RawWords = Val.getRawData();
763 for (unsigned i = 0; i != NWords; ++i) {
764 emitSignedInt64(Vals, RawWords[i]);
766 Code = bitc::CST_CODE_WIDE_INTEGER;
770 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
771 const ValueEnumerator &VE,
772 BitstreamWriter &Stream, bool isGlobal) {
773 if (FirstVal == LastVal) return;
775 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
777 unsigned AggregateAbbrev = 0;
778 unsigned String8Abbrev = 0;
779 unsigned CString7Abbrev = 0;
780 unsigned CString6Abbrev = 0;
781 // If this is a constant pool for the module, emit module-specific abbrevs.
783 // Abbrev for CST_CODE_AGGREGATE.
784 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
785 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
786 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
787 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
788 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
790 // Abbrev for CST_CODE_STRING.
791 Abbv = new BitCodeAbbrev();
792 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
793 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
794 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
795 String8Abbrev = Stream.EmitAbbrev(Abbv);
796 // Abbrev for CST_CODE_CSTRING.
797 Abbv = new BitCodeAbbrev();
798 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
799 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
800 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
801 CString7Abbrev = Stream.EmitAbbrev(Abbv);
802 // Abbrev for CST_CODE_CSTRING.
803 Abbv = new BitCodeAbbrev();
804 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
805 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
806 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
807 CString6Abbrev = Stream.EmitAbbrev(Abbv);
810 SmallVector<uint64_t, 64> Record;
812 const ValueEnumerator::ValueList &Vals = VE.getValues();
814 for (unsigned i = FirstVal; i != LastVal; ++i) {
815 const Value *V = Vals[i].first;
816 // If we need to switch types, do so now.
817 if (V->getType() != LastTy) {
818 LastTy = V->getType();
819 Record.push_back(VE.getTypeID(LastTy));
820 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
821 CONSTANTS_SETTYPE_ABBREV);
825 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
826 Record.push_back(unsigned(IA->hasSideEffects()) |
827 unsigned(IA->isAlignStack()) << 1 |
828 unsigned(IA->getDialect()&1) << 2);
830 // Add the asm string.
831 const std::string &AsmStr = IA->getAsmString();
832 Record.push_back(AsmStr.size());
833 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
834 Record.push_back(AsmStr[i]);
836 // Add the constraint string.
837 const std::string &ConstraintStr = IA->getConstraintString();
838 Record.push_back(ConstraintStr.size());
839 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
840 Record.push_back(ConstraintStr[i]);
841 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
845 const Constant *C = cast<Constant>(V);
847 unsigned AbbrevToUse = 0;
848 if (C->isNullValue()) {
849 Code = bitc::CST_CODE_NULL;
850 } else if (isa<UndefValue>(C)) {
851 Code = bitc::CST_CODE_UNDEF;
852 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
853 EmitAPInt(Record, Code, AbbrevToUse, IV->getValue());
854 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
855 Code = bitc::CST_CODE_FLOAT;
856 Type *Ty = CFP->getType();
857 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
858 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
859 } else if (Ty->isX86_FP80Ty()) {
860 // api needed to prevent premature destruction
861 // bits are not in the same order as a normal i80 APInt, compensate.
862 APInt api = CFP->getValueAPF().bitcastToAPInt();
863 const uint64_t *p = api.getRawData();
864 Record.push_back((p[1] << 48) | (p[0] >> 16));
865 Record.push_back(p[0] & 0xffffLL);
866 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
867 APInt api = CFP->getValueAPF().bitcastToAPInt();
868 const uint64_t *p = api.getRawData();
869 Record.push_back(p[0]);
870 Record.push_back(p[1]);
872 assert (0 && "Unknown FP type!");
874 } else if (isa<ConstantDataSequential>(C) &&
875 cast<ConstantDataSequential>(C)->isString()) {
876 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
877 // Emit constant strings specially.
878 unsigned NumElts = Str->getNumElements();
879 // If this is a null-terminated string, use the denser CSTRING encoding.
880 if (Str->isCString()) {
881 Code = bitc::CST_CODE_CSTRING;
882 --NumElts; // Don't encode the null, which isn't allowed by char6.
884 Code = bitc::CST_CODE_STRING;
885 AbbrevToUse = String8Abbrev;
887 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
888 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
889 for (unsigned i = 0; i != NumElts; ++i) {
890 unsigned char V = Str->getElementAsInteger(i);
892 isCStr7 &= (V & 128) == 0;
894 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
898 AbbrevToUse = CString6Abbrev;
900 AbbrevToUse = CString7Abbrev;
901 } else if (const ConstantDataSequential *CDS =
902 dyn_cast<ConstantDataSequential>(C)) {
903 Code = bitc::CST_CODE_DATA;
904 Type *EltTy = CDS->getType()->getElementType();
905 if (isa<IntegerType>(EltTy)) {
906 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
907 Record.push_back(CDS->getElementAsInteger(i));
908 } else if (EltTy->isFloatTy()) {
909 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
910 union { float F; uint32_t I; };
911 F = CDS->getElementAsFloat(i);
915 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
916 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
917 union { double F; uint64_t I; };
918 F = CDS->getElementAsDouble(i);
922 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
923 isa<ConstantVector>(C)) {
924 Code = bitc::CST_CODE_AGGREGATE;
925 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
926 Record.push_back(VE.getValueID(C->getOperand(i)));
927 AbbrevToUse = AggregateAbbrev;
928 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
929 switch (CE->getOpcode()) {
931 if (Instruction::isCast(CE->getOpcode())) {
932 Code = bitc::CST_CODE_CE_CAST;
933 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
934 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
935 Record.push_back(VE.getValueID(C->getOperand(0)));
936 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
938 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
939 Code = bitc::CST_CODE_CE_BINOP;
940 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
941 Record.push_back(VE.getValueID(C->getOperand(0)));
942 Record.push_back(VE.getValueID(C->getOperand(1)));
943 uint64_t Flags = GetOptimizationFlags(CE);
945 Record.push_back(Flags);
948 case Instruction::GetElementPtr:
949 Code = bitc::CST_CODE_CE_GEP;
950 if (cast<GEPOperator>(C)->isInBounds())
951 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
952 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
953 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
954 Record.push_back(VE.getValueID(C->getOperand(i)));
957 case Instruction::Select:
958 Code = bitc::CST_CODE_CE_SELECT;
959 Record.push_back(VE.getValueID(C->getOperand(0)));
960 Record.push_back(VE.getValueID(C->getOperand(1)));
961 Record.push_back(VE.getValueID(C->getOperand(2)));
963 case Instruction::ExtractElement:
964 Code = bitc::CST_CODE_CE_EXTRACTELT;
965 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
966 Record.push_back(VE.getValueID(C->getOperand(0)));
967 Record.push_back(VE.getValueID(C->getOperand(1)));
969 case Instruction::InsertElement:
970 Code = bitc::CST_CODE_CE_INSERTELT;
971 Record.push_back(VE.getValueID(C->getOperand(0)));
972 Record.push_back(VE.getValueID(C->getOperand(1)));
973 Record.push_back(VE.getValueID(C->getOperand(2)));
975 case Instruction::ShuffleVector:
976 // If the return type and argument types are the same, this is a
977 // standard shufflevector instruction. If the types are different,
978 // then the shuffle is widening or truncating the input vectors, and
979 // the argument type must also be encoded.
980 if (C->getType() == C->getOperand(0)->getType()) {
981 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
983 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
984 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
986 Record.push_back(VE.getValueID(C->getOperand(0)));
987 Record.push_back(VE.getValueID(C->getOperand(1)));
988 Record.push_back(VE.getValueID(C->getOperand(2)));
990 case Instruction::ICmp:
991 case Instruction::FCmp:
992 Code = bitc::CST_CODE_CE_CMP;
993 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
994 Record.push_back(VE.getValueID(C->getOperand(0)));
995 Record.push_back(VE.getValueID(C->getOperand(1)));
996 Record.push_back(CE->getPredicate());
999 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1000 Code = bitc::CST_CODE_BLOCKADDRESS;
1001 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1002 Record.push_back(VE.getValueID(BA->getFunction()));
1003 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1008 llvm_unreachable("Unknown constant!");
1010 Stream.EmitRecord(Code, Record, AbbrevToUse);
1017 static void WriteModuleConstants(const ValueEnumerator &VE,
1018 BitstreamWriter &Stream) {
1019 const ValueEnumerator::ValueList &Vals = VE.getValues();
1021 // Find the first constant to emit, which is the first non-globalvalue value.
1022 // We know globalvalues have been emitted by WriteModuleInfo.
1023 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1024 if (!isa<GlobalValue>(Vals[i].first)) {
1025 WriteConstants(i, Vals.size(), VE, Stream, true);
1031 /// PushValueAndType - The file has to encode both the value and type id for
1032 /// many values, because we need to know what type to create for forward
1033 /// references. However, most operands are not forward references, so this type
1034 /// field is not needed.
1036 /// This function adds V's value ID to Vals. If the value ID is higher than the
1037 /// instruction ID, then it is a forward reference, and it also includes the
1038 /// type ID. The value ID that is written is encoded relative to the InstID.
1039 static bool PushValueAndType(const Value *V, unsigned InstID,
1040 SmallVector<unsigned, 64> &Vals,
1041 ValueEnumerator &VE) {
1042 unsigned ValID = VE.getValueID(V);
1043 // Make encoding relative to the InstID.
1044 Vals.push_back(InstID - ValID);
1045 if (ValID >= InstID) {
1046 Vals.push_back(VE.getTypeID(V->getType()));
1052 /// pushValue - Like PushValueAndType, but where the type of the value is
1053 /// omitted (perhaps it was already encoded in an earlier operand).
1054 static void pushValue(const Value *V, unsigned InstID,
1055 SmallVector<unsigned, 64> &Vals,
1056 ValueEnumerator &VE) {
1057 unsigned ValID = VE.getValueID(V);
1058 Vals.push_back(InstID - ValID);
1061 static void pushValue64(const Value *V, unsigned InstID,
1062 SmallVector<uint64_t, 128> &Vals,
1063 ValueEnumerator &VE) {
1064 uint64_t ValID = VE.getValueID(V);
1065 Vals.push_back(InstID - ValID);
1068 static void pushValueSigned(const Value *V, unsigned InstID,
1069 SmallVector<uint64_t, 128> &Vals,
1070 ValueEnumerator &VE) {
1071 unsigned ValID = VE.getValueID(V);
1072 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1073 emitSignedInt64(Vals, diff);
1076 /// WriteInstruction - Emit an instruction to the specified stream.
1077 static void WriteInstruction(const Instruction &I, unsigned InstID,
1078 ValueEnumerator &VE, BitstreamWriter &Stream,
1079 SmallVector<unsigned, 64> &Vals) {
1081 unsigned AbbrevToUse = 0;
1082 VE.setInstructionID(&I);
1083 switch (I.getOpcode()) {
1085 if (Instruction::isCast(I.getOpcode())) {
1086 Code = bitc::FUNC_CODE_INST_CAST;
1087 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1088 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1089 Vals.push_back(VE.getTypeID(I.getType()));
1090 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1092 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1093 Code = bitc::FUNC_CODE_INST_BINOP;
1094 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1095 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1096 pushValue(I.getOperand(1), InstID, Vals, VE);
1097 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1098 uint64_t Flags = GetOptimizationFlags(&I);
1100 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1101 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1102 Vals.push_back(Flags);
1107 case Instruction::GetElementPtr:
1108 Code = bitc::FUNC_CODE_INST_GEP;
1109 if (cast<GEPOperator>(&I)->isInBounds())
1110 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1111 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1112 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1114 case Instruction::ExtractValue: {
1115 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1116 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1117 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1118 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1122 case Instruction::InsertValue: {
1123 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1124 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1125 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1126 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1127 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1131 case Instruction::Select:
1132 Code = bitc::FUNC_CODE_INST_VSELECT;
1133 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1134 pushValue(I.getOperand(2), InstID, Vals, VE);
1135 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1137 case Instruction::ExtractElement:
1138 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1139 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1140 pushValue(I.getOperand(1), InstID, Vals, VE);
1142 case Instruction::InsertElement:
1143 Code = bitc::FUNC_CODE_INST_INSERTELT;
1144 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1145 pushValue(I.getOperand(1), InstID, Vals, VE);
1146 pushValue(I.getOperand(2), InstID, Vals, VE);
1148 case Instruction::ShuffleVector:
1149 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1150 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1151 pushValue(I.getOperand(1), InstID, Vals, VE);
1152 pushValue(I.getOperand(2), InstID, Vals, VE);
1154 case Instruction::ICmp:
1155 case Instruction::FCmp:
1156 // compare returning Int1Ty or vector of Int1Ty
1157 Code = bitc::FUNC_CODE_INST_CMP2;
1158 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1159 pushValue(I.getOperand(1), InstID, Vals, VE);
1160 Vals.push_back(cast<CmpInst>(I).getPredicate());
1163 case Instruction::Ret:
1165 Code = bitc::FUNC_CODE_INST_RET;
1166 unsigned NumOperands = I.getNumOperands();
1167 if (NumOperands == 0)
1168 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1169 else if (NumOperands == 1) {
1170 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1171 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1173 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1174 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1178 case Instruction::Br:
1180 Code = bitc::FUNC_CODE_INST_BR;
1181 BranchInst &II = cast<BranchInst>(I);
1182 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1183 if (II.isConditional()) {
1184 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1185 pushValue(II.getCondition(), InstID, Vals, VE);
1189 case Instruction::Switch:
1191 // Redefine Vals, since here we need to use 64 bit values
1192 // explicitly to store large APInt numbers.
1193 SmallVector<uint64_t, 128> Vals64;
1195 Code = bitc::FUNC_CODE_INST_SWITCH;
1196 SwitchInst &SI = cast<SwitchInst>(I);
1198 uint32_t SwitchRecordHeader = SI.hash() | (SWITCH_INST_MAGIC << 16);
1199 Vals64.push_back(SwitchRecordHeader);
1201 Vals64.push_back(VE.getTypeID(SI.getCondition()->getType()));
1202 pushValue64(SI.getCondition(), InstID, Vals64, VE);
1203 Vals64.push_back(VE.getValueID(SI.getDefaultDest()));
1204 Vals64.push_back(SI.getNumCases());
1205 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
1207 IntegersSubset& CaseRanges = i.getCaseValueEx();
1208 unsigned Code, Abbrev; // will unused.
1210 if (CaseRanges.isSingleNumber()) {
1211 Vals64.push_back(1/*NumItems = 1*/);
1212 Vals64.push_back(true/*IsSingleNumber = true*/);
1213 EmitAPInt(Vals64, Code, Abbrev, CaseRanges.getSingleNumber(0), true);
1216 Vals64.push_back(CaseRanges.getNumItems());
1218 if (CaseRanges.isSingleNumbersOnly()) {
1219 for (unsigned ri = 0, rn = CaseRanges.getNumItems();
1222 Vals64.push_back(true/*IsSingleNumber = true*/);
1224 EmitAPInt(Vals64, Code, Abbrev,
1225 CaseRanges.getSingleNumber(ri), true);
1228 for (unsigned ri = 0, rn = CaseRanges.getNumItems();
1230 IntegersSubset::Range r = CaseRanges.getItem(ri);
1231 bool IsSingleNumber = CaseRanges.isSingleNumber(ri);
1233 Vals64.push_back(IsSingleNumber);
1235 EmitAPInt(Vals64, Code, Abbrev, r.getLow(), true);
1236 if (!IsSingleNumber)
1237 EmitAPInt(Vals64, Code, Abbrev, r.getHigh(), true);
1240 Vals64.push_back(VE.getValueID(i.getCaseSuccessor()));
1243 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1245 // Also do expected action - clear external Vals collection:
1250 case Instruction::IndirectBr:
1251 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1252 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1253 // Encode the address operand as relative, but not the basic blocks.
1254 pushValue(I.getOperand(0), InstID, Vals, VE);
1255 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1256 Vals.push_back(VE.getValueID(I.getOperand(i)));
1259 case Instruction::Invoke: {
1260 const InvokeInst *II = cast<InvokeInst>(&I);
1261 const Value *Callee(II->getCalledValue());
1262 PointerType *PTy = cast<PointerType>(Callee->getType());
1263 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1264 Code = bitc::FUNC_CODE_INST_INVOKE;
1266 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1267 Vals.push_back(II->getCallingConv());
1268 Vals.push_back(VE.getValueID(II->getNormalDest()));
1269 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1270 PushValueAndType(Callee, InstID, Vals, VE);
1272 // Emit value #'s for the fixed parameters.
1273 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1274 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1276 // Emit type/value pairs for varargs params.
1277 if (FTy->isVarArg()) {
1278 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1280 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1284 case Instruction::Resume:
1285 Code = bitc::FUNC_CODE_INST_RESUME;
1286 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1288 case Instruction::Unreachable:
1289 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1290 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1293 case Instruction::PHI: {
1294 const PHINode &PN = cast<PHINode>(I);
1295 Code = bitc::FUNC_CODE_INST_PHI;
1296 // With the newer instruction encoding, forward references could give
1297 // negative valued IDs. This is most common for PHIs, so we use
1299 SmallVector<uint64_t, 128> Vals64;
1300 Vals64.push_back(VE.getTypeID(PN.getType()));
1301 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1302 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1303 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1305 // Emit a Vals64 vector and exit.
1306 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1311 case Instruction::LandingPad: {
1312 const LandingPadInst &LP = cast<LandingPadInst>(I);
1313 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1314 Vals.push_back(VE.getTypeID(LP.getType()));
1315 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1316 Vals.push_back(LP.isCleanup());
1317 Vals.push_back(LP.getNumClauses());
1318 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1320 Vals.push_back(LandingPadInst::Catch);
1322 Vals.push_back(LandingPadInst::Filter);
1323 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1328 case Instruction::Alloca:
1329 Code = bitc::FUNC_CODE_INST_ALLOCA;
1330 Vals.push_back(VE.getTypeID(I.getType()));
1331 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1332 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1333 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1336 case Instruction::Load:
1337 if (cast<LoadInst>(I).isAtomic()) {
1338 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1339 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1341 Code = bitc::FUNC_CODE_INST_LOAD;
1342 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1343 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1345 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1346 Vals.push_back(cast<LoadInst>(I).isVolatile());
1347 if (cast<LoadInst>(I).isAtomic()) {
1348 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1349 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1352 case Instruction::Store:
1353 if (cast<StoreInst>(I).isAtomic())
1354 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1356 Code = bitc::FUNC_CODE_INST_STORE;
1357 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1358 pushValue(I.getOperand(0), InstID, Vals, VE); // val.
1359 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1360 Vals.push_back(cast<StoreInst>(I).isVolatile());
1361 if (cast<StoreInst>(I).isAtomic()) {
1362 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1363 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1366 case Instruction::AtomicCmpXchg:
1367 Code = bitc::FUNC_CODE_INST_CMPXCHG;
1368 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1369 pushValue(I.getOperand(1), InstID, Vals, VE); // cmp.
1370 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
1371 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1372 Vals.push_back(GetEncodedOrdering(
1373 cast<AtomicCmpXchgInst>(I).getOrdering()));
1374 Vals.push_back(GetEncodedSynchScope(
1375 cast<AtomicCmpXchgInst>(I).getSynchScope()));
1377 case Instruction::AtomicRMW:
1378 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1379 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1380 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
1381 Vals.push_back(GetEncodedRMWOperation(
1382 cast<AtomicRMWInst>(I).getOperation()));
1383 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1384 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1385 Vals.push_back(GetEncodedSynchScope(
1386 cast<AtomicRMWInst>(I).getSynchScope()));
1388 case Instruction::Fence:
1389 Code = bitc::FUNC_CODE_INST_FENCE;
1390 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1391 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1393 case Instruction::Call: {
1394 const CallInst &CI = cast<CallInst>(I);
1395 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1396 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1398 Code = bitc::FUNC_CODE_INST_CALL;
1400 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1401 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1402 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1404 // Emit value #'s for the fixed parameters.
1405 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1406 // Check for labels (can happen with asm labels).
1407 if (FTy->getParamType(i)->isLabelTy())
1408 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
1410 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
1413 // Emit type/value pairs for varargs params.
1414 if (FTy->isVarArg()) {
1415 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1417 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1421 case Instruction::VAArg:
1422 Code = bitc::FUNC_CODE_INST_VAARG;
1423 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1424 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
1425 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1429 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1433 // Emit names for globals/functions etc.
1434 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1435 const ValueEnumerator &VE,
1436 BitstreamWriter &Stream) {
1437 if (VST.empty()) return;
1438 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1440 // FIXME: Set up the abbrev, we know how many values there are!
1441 // FIXME: We know if the type names can use 7-bit ascii.
1442 SmallVector<unsigned, 64> NameVals;
1444 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1447 const ValueName &Name = *SI;
1449 // Figure out the encoding to use for the name.
1451 bool isChar6 = true;
1452 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1455 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1456 if ((unsigned char)*C & 128) {
1458 break; // don't bother scanning the rest.
1462 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1464 // VST_ENTRY: [valueid, namechar x N]
1465 // VST_BBENTRY: [bbid, namechar x N]
1467 if (isa<BasicBlock>(SI->getValue())) {
1468 Code = bitc::VST_CODE_BBENTRY;
1470 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1472 Code = bitc::VST_CODE_ENTRY;
1474 AbbrevToUse = VST_ENTRY_6_ABBREV;
1476 AbbrevToUse = VST_ENTRY_7_ABBREV;
1479 NameVals.push_back(VE.getValueID(SI->getValue()));
1480 for (const char *P = Name.getKeyData(),
1481 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1482 NameVals.push_back((unsigned char)*P);
1484 // Emit the finished record.
1485 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1491 /// WriteFunction - Emit a function body to the module stream.
1492 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1493 BitstreamWriter &Stream) {
1494 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1495 VE.incorporateFunction(F);
1497 SmallVector<unsigned, 64> Vals;
1499 // Emit the number of basic blocks, so the reader can create them ahead of
1501 Vals.push_back(VE.getBasicBlocks().size());
1502 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1505 // If there are function-local constants, emit them now.
1506 unsigned CstStart, CstEnd;
1507 VE.getFunctionConstantRange(CstStart, CstEnd);
1508 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1510 // If there is function-local metadata, emit it now.
1511 WriteFunctionLocalMetadata(F, VE, Stream);
1513 // Keep a running idea of what the instruction ID is.
1514 unsigned InstID = CstEnd;
1516 bool NeedsMetadataAttachment = false;
1520 // Finally, emit all the instructions, in order.
1521 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1522 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1524 WriteInstruction(*I, InstID, VE, Stream, Vals);
1526 if (!I->getType()->isVoidTy())
1529 // If the instruction has metadata, write a metadata attachment later.
1530 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1532 // If the instruction has a debug location, emit it.
1533 DebugLoc DL = I->getDebugLoc();
1534 if (DL.isUnknown()) {
1536 } else if (DL == LastDL) {
1537 // Just repeat the same debug loc as last time.
1538 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1541 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1543 Vals.push_back(DL.getLine());
1544 Vals.push_back(DL.getCol());
1545 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1546 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1547 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1554 // Emit names for all the instructions etc.
1555 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1557 if (NeedsMetadataAttachment)
1558 WriteMetadataAttachment(F, VE, Stream);
1563 // Emit blockinfo, which defines the standard abbreviations etc.
1564 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1565 // We only want to emit block info records for blocks that have multiple
1566 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
1567 // Other blocks can define their abbrevs inline.
1568 Stream.EnterBlockInfoBlock(2);
1570 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1571 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1572 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1573 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1574 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1575 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1576 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1577 Abbv) != VST_ENTRY_8_ABBREV)
1578 llvm_unreachable("Unexpected abbrev ordering!");
1581 { // 7-bit fixed width VST_ENTRY strings.
1582 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1583 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1584 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1585 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1586 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1587 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1588 Abbv) != VST_ENTRY_7_ABBREV)
1589 llvm_unreachable("Unexpected abbrev ordering!");
1591 { // 6-bit char6 VST_ENTRY strings.
1592 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1593 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1594 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1595 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1596 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1597 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1598 Abbv) != VST_ENTRY_6_ABBREV)
1599 llvm_unreachable("Unexpected abbrev ordering!");
1601 { // 6-bit char6 VST_BBENTRY strings.
1602 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1603 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1604 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1605 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1606 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1607 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1608 Abbv) != VST_BBENTRY_6_ABBREV)
1609 llvm_unreachable("Unexpected abbrev ordering!");
1614 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1615 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1616 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1617 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1618 Log2_32_Ceil(VE.getTypes().size()+1)));
1619 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1620 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1621 llvm_unreachable("Unexpected abbrev ordering!");
1624 { // INTEGER abbrev for CONSTANTS_BLOCK.
1625 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1626 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1627 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1628 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1629 Abbv) != CONSTANTS_INTEGER_ABBREV)
1630 llvm_unreachable("Unexpected abbrev ordering!");
1633 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1634 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1635 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1636 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1637 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1638 Log2_32_Ceil(VE.getTypes().size()+1)));
1639 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1641 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1642 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1643 llvm_unreachable("Unexpected abbrev ordering!");
1645 { // NULL abbrev for CONSTANTS_BLOCK.
1646 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1647 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1648 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1649 Abbv) != CONSTANTS_NULL_Abbrev)
1650 llvm_unreachable("Unexpected abbrev ordering!");
1653 // FIXME: This should only use space for first class types!
1655 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1656 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1657 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1658 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1659 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1660 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1661 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1662 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1663 llvm_unreachable("Unexpected abbrev ordering!");
1665 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1666 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1667 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1668 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1669 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1670 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1671 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1672 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1673 llvm_unreachable("Unexpected abbrev ordering!");
1675 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1676 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1677 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1678 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1679 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1680 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1681 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1682 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1683 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1684 llvm_unreachable("Unexpected abbrev ordering!");
1686 { // INST_CAST abbrev for FUNCTION_BLOCK.
1687 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1688 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1689 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1690 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1691 Log2_32_Ceil(VE.getTypes().size()+1)));
1692 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1693 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1694 Abbv) != FUNCTION_INST_CAST_ABBREV)
1695 llvm_unreachable("Unexpected abbrev ordering!");
1698 { // INST_RET abbrev for FUNCTION_BLOCK.
1699 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1700 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1701 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1702 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1703 llvm_unreachable("Unexpected abbrev ordering!");
1705 { // INST_RET abbrev for FUNCTION_BLOCK.
1706 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1707 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1708 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1709 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1710 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1711 llvm_unreachable("Unexpected abbrev ordering!");
1713 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1714 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1715 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1716 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1717 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1718 llvm_unreachable("Unexpected abbrev ordering!");
1724 // Sort the Users based on the order in which the reader parses the bitcode
1726 static bool bitcodereader_order(const User *lhs, const User *rhs) {
1731 static void WriteUseList(const Value *V, const ValueEnumerator &VE,
1732 BitstreamWriter &Stream) {
1734 // One or zero uses can't get out of order.
1735 if (V->use_empty() || V->hasNUses(1))
1738 // Make a copy of the in-memory use-list for sorting.
1739 unsigned UseListSize = std::distance(V->use_begin(), V->use_end());
1740 SmallVector<const User*, 8> UseList;
1741 UseList.reserve(UseListSize);
1742 for (Value::const_use_iterator I = V->use_begin(), E = V->use_end();
1745 UseList.push_back(U);
1748 // Sort the copy based on the order read by the BitcodeReader.
1749 std::sort(UseList.begin(), UseList.end(), bitcodereader_order);
1751 // TODO: Generate a diff between the BitcodeWriter in-memory use-list and the
1752 // sorted list (i.e., the expected BitcodeReader in-memory use-list).
1754 // TODO: Emit the USELIST_CODE_ENTRYs.
1757 static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE,
1758 BitstreamWriter &Stream) {
1759 VE.incorporateFunction(*F);
1761 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1763 WriteUseList(AI, VE, Stream);
1764 for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE;
1766 WriteUseList(BB, VE, Stream);
1767 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
1769 WriteUseList(II, VE, Stream);
1770 for (User::const_op_iterator OI = II->op_begin(), E = II->op_end();
1772 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
1773 isa<InlineAsm>(*OI))
1774 WriteUseList(*OI, VE, Stream);
1782 static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE,
1783 BitstreamWriter &Stream) {
1784 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
1786 // XXX: this modifies the module, but in a way that should never change the
1787 // behavior of any pass or codegen in LLVM. The problem is that GVs may
1788 // contain entries in the use_list that do not exist in the Module and are
1789 // not stored in the .bc file.
1790 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1792 I->removeDeadConstantUsers();
1794 // Write the global variables.
1795 for (Module::const_global_iterator GI = M->global_begin(),
1796 GE = M->global_end(); GI != GE; ++GI) {
1797 WriteUseList(GI, VE, Stream);
1799 // Write the global variable initializers.
1800 if (GI->hasInitializer())
1801 WriteUseList(GI->getInitializer(), VE, Stream);
1804 // Write the functions.
1805 for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
1806 WriteUseList(FI, VE, Stream);
1807 if (!FI->isDeclaration())
1808 WriteFunctionUseList(FI, VE, Stream);
1811 // Write the aliases.
1812 for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end();
1814 WriteUseList(AI, VE, Stream);
1815 WriteUseList(AI->getAliasee(), VE, Stream);
1821 /// WriteModule - Emit the specified module to the bitstream.
1822 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1823 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1825 SmallVector<unsigned, 1> Vals;
1826 unsigned CurVersion = 1;
1827 Vals.push_back(CurVersion);
1828 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1830 // Analyze the module, enumerating globals, functions, etc.
1831 ValueEnumerator VE(M);
1833 // Emit blockinfo, which defines the standard abbreviations etc.
1834 WriteBlockInfo(VE, Stream);
1836 // Emit information about parameter attributes.
1837 WriteAttributeTable(VE, Stream);
1839 // Emit information describing all of the types in the module.
1840 WriteTypeTable(VE, Stream);
1842 // Emit top-level description of module, including target triple, inline asm,
1843 // descriptors for global variables, and function prototype info.
1844 WriteModuleInfo(M, VE, Stream);
1847 WriteModuleConstants(VE, Stream);
1850 WriteModuleMetadata(M, VE, Stream);
1853 WriteModuleMetadataStore(M, Stream);
1855 // Emit names for globals/functions etc.
1856 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1859 if (EnablePreserveUseListOrdering)
1860 WriteModuleUseLists(M, VE, Stream);
1862 // Emit function bodies.
1863 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1864 if (!F->isDeclaration())
1865 WriteFunction(*F, VE, Stream);
1870 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1871 /// header and trailer to make it compatible with the system archiver. To do
1872 /// this we emit the following header, and then emit a trailer that pads the
1873 /// file out to be a multiple of 16 bytes.
1875 /// struct bc_header {
1876 /// uint32_t Magic; // 0x0B17C0DE
1877 /// uint32_t Version; // Version, currently always 0.
1878 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1879 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1880 /// uint32_t CPUType; // CPU specifier.
1881 /// ... potentially more later ...
1884 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1885 DarwinBCHeaderSize = 5*4
1888 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
1889 uint32_t &Position) {
1890 Buffer[Position + 0] = (unsigned char) (Value >> 0);
1891 Buffer[Position + 1] = (unsigned char) (Value >> 8);
1892 Buffer[Position + 2] = (unsigned char) (Value >> 16);
1893 Buffer[Position + 3] = (unsigned char) (Value >> 24);
1897 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
1899 unsigned CPUType = ~0U;
1901 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1902 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1903 // number from /usr/include/mach/machine.h. It is ok to reproduce the
1904 // specific constants here because they are implicitly part of the Darwin ABI.
1906 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1907 DARWIN_CPU_TYPE_X86 = 7,
1908 DARWIN_CPU_TYPE_ARM = 12,
1909 DARWIN_CPU_TYPE_POWERPC = 18
1912 Triple::ArchType Arch = TT.getArch();
1913 if (Arch == Triple::x86_64)
1914 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1915 else if (Arch == Triple::x86)
1916 CPUType = DARWIN_CPU_TYPE_X86;
1917 else if (Arch == Triple::ppc)
1918 CPUType = DARWIN_CPU_TYPE_POWERPC;
1919 else if (Arch == Triple::ppc64)
1920 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1921 else if (Arch == Triple::arm || Arch == Triple::thumb)
1922 CPUType = DARWIN_CPU_TYPE_ARM;
1924 // Traditional Bitcode starts after header.
1925 assert(Buffer.size() >= DarwinBCHeaderSize &&
1926 "Expected header size to be reserved");
1927 unsigned BCOffset = DarwinBCHeaderSize;
1928 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
1930 // Write the magic and version.
1931 unsigned Position = 0;
1932 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
1933 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
1934 WriteInt32ToBuffer(BCOffset , Buffer, Position);
1935 WriteInt32ToBuffer(BCSize , Buffer, Position);
1936 WriteInt32ToBuffer(CPUType , Buffer, Position);
1938 // If the file is not a multiple of 16 bytes, insert dummy padding.
1939 while (Buffer.size() & 15)
1940 Buffer.push_back(0);
1943 /// WriteBitcodeToFile - Write the specified module to the specified output
1945 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1946 SmallVector<char, 1024> Buffer;
1947 Buffer.reserve(256*1024);
1949 // If this is darwin or another generic macho target, reserve space for the
1951 Triple TT(M->getTargetTriple());
1952 if (TT.isOSDarwin())
1953 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
1955 // Emit the module into the buffer.
1957 BitstreamWriter Stream(Buffer);
1959 // Emit the file header.
1960 Stream.Emit((unsigned)'B', 8);
1961 Stream.Emit((unsigned)'C', 8);
1962 Stream.Emit(0x0, 4);
1963 Stream.Emit(0xC, 4);
1964 Stream.Emit(0xE, 4);
1965 Stream.Emit(0xD, 4);
1968 WriteModule(M, Stream);
1971 if (TT.isOSDarwin())
1972 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
1974 // Write the generated bitstream to "Out".
1975 Out.write((char*)&Buffer.front(), Buffer.size());