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