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