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