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