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