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 "ValueEnumerator.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/Triple.h" 17 #include "llvm/Analysis/BlockFrequencyInfo.h" 18 #include "llvm/Analysis/BlockFrequencyInfoImpl.h" 19 #include "llvm/Analysis/BranchProbabilityInfo.h" 20 #include "llvm/Analysis/LoopInfo.h" 21 #include "llvm/Bitcode/BitstreamWriter.h" 22 #include "llvm/Bitcode/LLVMBitCodes.h" 23 #include "llvm/Bitcode/ReaderWriter.h" 24 #include "llvm/IR/CallSite.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/DebugInfoMetadata.h" 27 #include "llvm/IR/DerivedTypes.h" 28 #include "llvm/IR/Dominators.h" 29 #include "llvm/IR/InlineAsm.h" 30 #include "llvm/IR/Instructions.h" 31 #include "llvm/IR/IntrinsicInst.h" 32 #include "llvm/IR/LLVMContext.h" 33 #include "llvm/IR/Module.h" 34 #include "llvm/IR/Operator.h" 35 #include "llvm/IR/UseListOrder.h" 36 #include "llvm/IR/ValueSymbolTable.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/Program.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include <cctype> 43 #include <map> 44 using namespace llvm; 45 46 /// These are manifest constants used by the bitcode writer. They do not need to 47 /// be kept in sync with the reader, but need to be consistent within this file. 48 enum { 49 // VALUE_SYMTAB_BLOCK abbrev id's. 50 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 51 VST_ENTRY_7_ABBREV, 52 VST_ENTRY_6_ABBREV, 53 VST_BBENTRY_6_ABBREV, 54 55 // CONSTANTS_BLOCK abbrev id's. 56 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 57 CONSTANTS_INTEGER_ABBREV, 58 CONSTANTS_CE_CAST_Abbrev, 59 CONSTANTS_NULL_Abbrev, 60 61 // FUNCTION_BLOCK abbrev id's. 62 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 63 FUNCTION_INST_BINOP_ABBREV, 64 FUNCTION_INST_BINOP_FLAGS_ABBREV, 65 FUNCTION_INST_CAST_ABBREV, 66 FUNCTION_INST_RET_VOID_ABBREV, 67 FUNCTION_INST_RET_VAL_ABBREV, 68 FUNCTION_INST_UNREACHABLE_ABBREV, 69 FUNCTION_INST_GEP_ABBREV, 70 }; 71 72 static unsigned GetEncodedCastOpcode(unsigned Opcode) { 73 switch (Opcode) { 74 default: llvm_unreachable("Unknown cast instruction!"); 75 case Instruction::Trunc : return bitc::CAST_TRUNC; 76 case Instruction::ZExt : return bitc::CAST_ZEXT; 77 case Instruction::SExt : return bitc::CAST_SEXT; 78 case Instruction::FPToUI : return bitc::CAST_FPTOUI; 79 case Instruction::FPToSI : return bitc::CAST_FPTOSI; 80 case Instruction::UIToFP : return bitc::CAST_UITOFP; 81 case Instruction::SIToFP : return bitc::CAST_SITOFP; 82 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC; 83 case Instruction::FPExt : return bitc::CAST_FPEXT; 84 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT; 85 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR; 86 case Instruction::BitCast : return bitc::CAST_BITCAST; 87 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST; 88 } 89 } 90 91 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) { 92 switch (Opcode) { 93 default: llvm_unreachable("Unknown binary instruction!"); 94 case Instruction::Add: 95 case Instruction::FAdd: return bitc::BINOP_ADD; 96 case Instruction::Sub: 97 case Instruction::FSub: return bitc::BINOP_SUB; 98 case Instruction::Mul: 99 case Instruction::FMul: return bitc::BINOP_MUL; 100 case Instruction::UDiv: return bitc::BINOP_UDIV; 101 case Instruction::FDiv: 102 case Instruction::SDiv: return bitc::BINOP_SDIV; 103 case Instruction::URem: return bitc::BINOP_UREM; 104 case Instruction::FRem: 105 case Instruction::SRem: return bitc::BINOP_SREM; 106 case Instruction::Shl: return bitc::BINOP_SHL; 107 case Instruction::LShr: return bitc::BINOP_LSHR; 108 case Instruction::AShr: return bitc::BINOP_ASHR; 109 case Instruction::And: return bitc::BINOP_AND; 110 case Instruction::Or: return bitc::BINOP_OR; 111 case Instruction::Xor: return bitc::BINOP_XOR; 112 } 113 } 114 115 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) { 116 switch (Op) { 117 default: llvm_unreachable("Unknown RMW operation!"); 118 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG; 119 case AtomicRMWInst::Add: return bitc::RMW_ADD; 120 case AtomicRMWInst::Sub: return bitc::RMW_SUB; 121 case AtomicRMWInst::And: return bitc::RMW_AND; 122 case AtomicRMWInst::Nand: return bitc::RMW_NAND; 123 case AtomicRMWInst::Or: return bitc::RMW_OR; 124 case AtomicRMWInst::Xor: return bitc::RMW_XOR; 125 case AtomicRMWInst::Max: return bitc::RMW_MAX; 126 case AtomicRMWInst::Min: return bitc::RMW_MIN; 127 case AtomicRMWInst::UMax: return bitc::RMW_UMAX; 128 case AtomicRMWInst::UMin: return bitc::RMW_UMIN; 129 } 130 } 131 132 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) { 133 switch (Ordering) { 134 case NotAtomic: return bitc::ORDERING_NOTATOMIC; 135 case Unordered: return bitc::ORDERING_UNORDERED; 136 case Monotonic: return bitc::ORDERING_MONOTONIC; 137 case Acquire: return bitc::ORDERING_ACQUIRE; 138 case Release: return bitc::ORDERING_RELEASE; 139 case AcquireRelease: return bitc::ORDERING_ACQREL; 140 case SequentiallyConsistent: return bitc::ORDERING_SEQCST; 141 } 142 llvm_unreachable("Invalid ordering"); 143 } 144 145 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) { 146 switch (SynchScope) { 147 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD; 148 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD; 149 } 150 llvm_unreachable("Invalid synch scope"); 151 } 152 153 static void WriteStringRecord(unsigned Code, StringRef Str, 154 unsigned AbbrevToUse, BitstreamWriter &Stream) { 155 SmallVector<unsigned, 64> Vals; 156 157 // Code: [strchar x N] 158 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 159 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i])) 160 AbbrevToUse = 0; 161 Vals.push_back(Str[i]); 162 } 163 164 // Emit the finished record. 165 Stream.EmitRecord(Code, Vals, AbbrevToUse); 166 } 167 168 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) { 169 switch (Kind) { 170 case Attribute::Alignment: 171 return bitc::ATTR_KIND_ALIGNMENT; 172 case Attribute::AlwaysInline: 173 return bitc::ATTR_KIND_ALWAYS_INLINE; 174 case Attribute::ArgMemOnly: 175 return bitc::ATTR_KIND_ARGMEMONLY; 176 case Attribute::Builtin: 177 return bitc::ATTR_KIND_BUILTIN; 178 case Attribute::ByVal: 179 return bitc::ATTR_KIND_BY_VAL; 180 case Attribute::Convergent: 181 return bitc::ATTR_KIND_CONVERGENT; 182 case Attribute::InAlloca: 183 return bitc::ATTR_KIND_IN_ALLOCA; 184 case Attribute::Cold: 185 return bitc::ATTR_KIND_COLD; 186 case Attribute::InaccessibleMemOnly: 187 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY; 188 case Attribute::InaccessibleMemOrArgMemOnly: 189 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY; 190 case Attribute::InlineHint: 191 return bitc::ATTR_KIND_INLINE_HINT; 192 case Attribute::InReg: 193 return bitc::ATTR_KIND_IN_REG; 194 case Attribute::JumpTable: 195 return bitc::ATTR_KIND_JUMP_TABLE; 196 case Attribute::MinSize: 197 return bitc::ATTR_KIND_MIN_SIZE; 198 case Attribute::Naked: 199 return bitc::ATTR_KIND_NAKED; 200 case Attribute::Nest: 201 return bitc::ATTR_KIND_NEST; 202 case Attribute::NoAlias: 203 return bitc::ATTR_KIND_NO_ALIAS; 204 case Attribute::NoBuiltin: 205 return bitc::ATTR_KIND_NO_BUILTIN; 206 case Attribute::NoCapture: 207 return bitc::ATTR_KIND_NO_CAPTURE; 208 case Attribute::NoDuplicate: 209 return bitc::ATTR_KIND_NO_DUPLICATE; 210 case Attribute::NoImplicitFloat: 211 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT; 212 case Attribute::NoInline: 213 return bitc::ATTR_KIND_NO_INLINE; 214 case Attribute::NoRecurse: 215 return bitc::ATTR_KIND_NO_RECURSE; 216 case Attribute::NonLazyBind: 217 return bitc::ATTR_KIND_NON_LAZY_BIND; 218 case Attribute::NonNull: 219 return bitc::ATTR_KIND_NON_NULL; 220 case Attribute::Dereferenceable: 221 return bitc::ATTR_KIND_DEREFERENCEABLE; 222 case Attribute::DereferenceableOrNull: 223 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL; 224 case Attribute::NoRedZone: 225 return bitc::ATTR_KIND_NO_RED_ZONE; 226 case Attribute::NoReturn: 227 return bitc::ATTR_KIND_NO_RETURN; 228 case Attribute::NoUnwind: 229 return bitc::ATTR_KIND_NO_UNWIND; 230 case Attribute::OptimizeForSize: 231 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE; 232 case Attribute::OptimizeNone: 233 return bitc::ATTR_KIND_OPTIMIZE_NONE; 234 case Attribute::ReadNone: 235 return bitc::ATTR_KIND_READ_NONE; 236 case Attribute::ReadOnly: 237 return bitc::ATTR_KIND_READ_ONLY; 238 case Attribute::Returned: 239 return bitc::ATTR_KIND_RETURNED; 240 case Attribute::ReturnsTwice: 241 return bitc::ATTR_KIND_RETURNS_TWICE; 242 case Attribute::SExt: 243 return bitc::ATTR_KIND_S_EXT; 244 case Attribute::StackAlignment: 245 return bitc::ATTR_KIND_STACK_ALIGNMENT; 246 case Attribute::StackProtect: 247 return bitc::ATTR_KIND_STACK_PROTECT; 248 case Attribute::StackProtectReq: 249 return bitc::ATTR_KIND_STACK_PROTECT_REQ; 250 case Attribute::StackProtectStrong: 251 return bitc::ATTR_KIND_STACK_PROTECT_STRONG; 252 case Attribute::SafeStack: 253 return bitc::ATTR_KIND_SAFESTACK; 254 case Attribute::StructRet: 255 return bitc::ATTR_KIND_STRUCT_RET; 256 case Attribute::SanitizeAddress: 257 return bitc::ATTR_KIND_SANITIZE_ADDRESS; 258 case Attribute::SanitizeThread: 259 return bitc::ATTR_KIND_SANITIZE_THREAD; 260 case Attribute::SanitizeMemory: 261 return bitc::ATTR_KIND_SANITIZE_MEMORY; 262 case Attribute::SwiftSelf: 263 return bitc::ATTR_KIND_SWIFT_SELF; 264 case Attribute::UWTable: 265 return bitc::ATTR_KIND_UW_TABLE; 266 case Attribute::ZExt: 267 return bitc::ATTR_KIND_Z_EXT; 268 case Attribute::EndAttrKinds: 269 llvm_unreachable("Can not encode end-attribute kinds marker."); 270 case Attribute::None: 271 llvm_unreachable("Can not encode none-attribute."); 272 } 273 274 llvm_unreachable("Trying to encode unknown attribute"); 275 } 276 277 static void WriteAttributeGroupTable(const ValueEnumerator &VE, 278 BitstreamWriter &Stream) { 279 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups(); 280 if (AttrGrps.empty()) return; 281 282 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3); 283 284 SmallVector<uint64_t, 64> Record; 285 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) { 286 AttributeSet AS = AttrGrps[i]; 287 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) { 288 AttributeSet A = AS.getSlotAttributes(i); 289 290 Record.push_back(VE.getAttributeGroupID(A)); 291 Record.push_back(AS.getSlotIndex(i)); 292 293 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0); 294 I != E; ++I) { 295 Attribute Attr = *I; 296 if (Attr.isEnumAttribute()) { 297 Record.push_back(0); 298 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 299 } else if (Attr.isIntAttribute()) { 300 Record.push_back(1); 301 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 302 Record.push_back(Attr.getValueAsInt()); 303 } else { 304 StringRef Kind = Attr.getKindAsString(); 305 StringRef Val = Attr.getValueAsString(); 306 307 Record.push_back(Val.empty() ? 3 : 4); 308 Record.append(Kind.begin(), Kind.end()); 309 Record.push_back(0); 310 if (!Val.empty()) { 311 Record.append(Val.begin(), Val.end()); 312 Record.push_back(0); 313 } 314 } 315 } 316 317 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record); 318 Record.clear(); 319 } 320 } 321 322 Stream.ExitBlock(); 323 } 324 325 static void WriteAttributeTable(const ValueEnumerator &VE, 326 BitstreamWriter &Stream) { 327 const std::vector<AttributeSet> &Attrs = VE.getAttributes(); 328 if (Attrs.empty()) return; 329 330 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3); 331 332 SmallVector<uint64_t, 64> Record; 333 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) { 334 const AttributeSet &A = Attrs[i]; 335 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) 336 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i))); 337 338 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record); 339 Record.clear(); 340 } 341 342 Stream.ExitBlock(); 343 } 344 345 /// WriteTypeTable - Write out the type table for a module. 346 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { 347 const ValueEnumerator::TypeList &TypeList = VE.getTypes(); 348 349 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */); 350 SmallVector<uint64_t, 64> TypeVals; 351 352 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies(); 353 354 // Abbrev for TYPE_CODE_POINTER. 355 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 356 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER)); 357 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 358 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0 359 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv); 360 361 // Abbrev for TYPE_CODE_FUNCTION. 362 Abbv = new BitCodeAbbrev(); 363 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION)); 364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg 365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 367 368 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv); 369 370 // Abbrev for TYPE_CODE_STRUCT_ANON. 371 Abbv = new BitCodeAbbrev(); 372 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON)); 373 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 374 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 375 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 376 377 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv); 378 379 // Abbrev for TYPE_CODE_STRUCT_NAME. 380 Abbv = new BitCodeAbbrev(); 381 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME)); 382 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 383 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 384 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv); 385 386 // Abbrev for TYPE_CODE_STRUCT_NAMED. 387 Abbv = new BitCodeAbbrev(); 388 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED)); 389 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 390 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 391 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 392 393 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv); 394 395 // Abbrev for TYPE_CODE_ARRAY. 396 Abbv = new BitCodeAbbrev(); 397 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY)); 398 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size 399 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 400 401 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv); 402 403 // Emit an entry count so the reader can reserve space. 404 TypeVals.push_back(TypeList.size()); 405 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals); 406 TypeVals.clear(); 407 408 // Loop over all of the types, emitting each in turn. 409 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { 410 Type *T = TypeList[i]; 411 int AbbrevToUse = 0; 412 unsigned Code = 0; 413 414 switch (T->getTypeID()) { 415 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break; 416 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break; 417 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break; 418 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break; 419 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break; 420 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break; 421 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break; 422 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break; 423 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break; 424 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break; 425 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break; 426 case Type::IntegerTyID: 427 // INTEGER: [width] 428 Code = bitc::TYPE_CODE_INTEGER; 429 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 430 break; 431 case Type::PointerTyID: { 432 PointerType *PTy = cast<PointerType>(T); 433 // POINTER: [pointee type, address space] 434 Code = bitc::TYPE_CODE_POINTER; 435 TypeVals.push_back(VE.getTypeID(PTy->getElementType())); 436 unsigned AddressSpace = PTy->getAddressSpace(); 437 TypeVals.push_back(AddressSpace); 438 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev; 439 break; 440 } 441 case Type::FunctionTyID: { 442 FunctionType *FT = cast<FunctionType>(T); 443 // FUNCTION: [isvararg, retty, paramty x N] 444 Code = bitc::TYPE_CODE_FUNCTION; 445 TypeVals.push_back(FT->isVarArg()); 446 TypeVals.push_back(VE.getTypeID(FT->getReturnType())); 447 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) 448 TypeVals.push_back(VE.getTypeID(FT->getParamType(i))); 449 AbbrevToUse = FunctionAbbrev; 450 break; 451 } 452 case Type::StructTyID: { 453 StructType *ST = cast<StructType>(T); 454 // STRUCT: [ispacked, eltty x N] 455 TypeVals.push_back(ST->isPacked()); 456 // Output all of the element types. 457 for (StructType::element_iterator I = ST->element_begin(), 458 E = ST->element_end(); I != E; ++I) 459 TypeVals.push_back(VE.getTypeID(*I)); 460 461 if (ST->isLiteral()) { 462 Code = bitc::TYPE_CODE_STRUCT_ANON; 463 AbbrevToUse = StructAnonAbbrev; 464 } else { 465 if (ST->isOpaque()) { 466 Code = bitc::TYPE_CODE_OPAQUE; 467 } else { 468 Code = bitc::TYPE_CODE_STRUCT_NAMED; 469 AbbrevToUse = StructNamedAbbrev; 470 } 471 472 // Emit the name if it is present. 473 if (!ST->getName().empty()) 474 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(), 475 StructNameAbbrev, Stream); 476 } 477 break; 478 } 479 case Type::ArrayTyID: { 480 ArrayType *AT = cast<ArrayType>(T); 481 // ARRAY: [numelts, eltty] 482 Code = bitc::TYPE_CODE_ARRAY; 483 TypeVals.push_back(AT->getNumElements()); 484 TypeVals.push_back(VE.getTypeID(AT->getElementType())); 485 AbbrevToUse = ArrayAbbrev; 486 break; 487 } 488 case Type::VectorTyID: { 489 VectorType *VT = cast<VectorType>(T); 490 // VECTOR [numelts, eltty] 491 Code = bitc::TYPE_CODE_VECTOR; 492 TypeVals.push_back(VT->getNumElements()); 493 TypeVals.push_back(VE.getTypeID(VT->getElementType())); 494 break; 495 } 496 } 497 498 // Emit the finished record. 499 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 500 TypeVals.clear(); 501 } 502 503 Stream.ExitBlock(); 504 } 505 506 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) { 507 switch (Linkage) { 508 case GlobalValue::ExternalLinkage: 509 return 0; 510 case GlobalValue::WeakAnyLinkage: 511 return 16; 512 case GlobalValue::AppendingLinkage: 513 return 2; 514 case GlobalValue::InternalLinkage: 515 return 3; 516 case GlobalValue::LinkOnceAnyLinkage: 517 return 18; 518 case GlobalValue::ExternalWeakLinkage: 519 return 7; 520 case GlobalValue::CommonLinkage: 521 return 8; 522 case GlobalValue::PrivateLinkage: 523 return 9; 524 case GlobalValue::WeakODRLinkage: 525 return 17; 526 case GlobalValue::LinkOnceODRLinkage: 527 return 19; 528 case GlobalValue::AvailableExternallyLinkage: 529 return 12; 530 } 531 llvm_unreachable("Invalid linkage"); 532 } 533 534 static unsigned getEncodedLinkage(const GlobalValue &GV) { 535 return getEncodedLinkage(GV.getLinkage()); 536 } 537 538 static unsigned getEncodedVisibility(const GlobalValue &GV) { 539 switch (GV.getVisibility()) { 540 case GlobalValue::DefaultVisibility: return 0; 541 case GlobalValue::HiddenVisibility: return 1; 542 case GlobalValue::ProtectedVisibility: return 2; 543 } 544 llvm_unreachable("Invalid visibility"); 545 } 546 547 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) { 548 switch (GV.getDLLStorageClass()) { 549 case GlobalValue::DefaultStorageClass: return 0; 550 case GlobalValue::DLLImportStorageClass: return 1; 551 case GlobalValue::DLLExportStorageClass: return 2; 552 } 553 llvm_unreachable("Invalid DLL storage class"); 554 } 555 556 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) { 557 switch (GV.getThreadLocalMode()) { 558 case GlobalVariable::NotThreadLocal: return 0; 559 case GlobalVariable::GeneralDynamicTLSModel: return 1; 560 case GlobalVariable::LocalDynamicTLSModel: return 2; 561 case GlobalVariable::InitialExecTLSModel: return 3; 562 case GlobalVariable::LocalExecTLSModel: return 4; 563 } 564 llvm_unreachable("Invalid TLS model"); 565 } 566 567 static unsigned getEncodedComdatSelectionKind(const Comdat &C) { 568 switch (C.getSelectionKind()) { 569 case Comdat::Any: 570 return bitc::COMDAT_SELECTION_KIND_ANY; 571 case Comdat::ExactMatch: 572 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH; 573 case Comdat::Largest: 574 return bitc::COMDAT_SELECTION_KIND_LARGEST; 575 case Comdat::NoDuplicates: 576 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES; 577 case Comdat::SameSize: 578 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE; 579 } 580 llvm_unreachable("Invalid selection kind"); 581 } 582 583 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) { 584 SmallVector<unsigned, 64> Vals; 585 for (const Comdat *C : VE.getComdats()) { 586 // COMDAT: [selection_kind, name] 587 Vals.push_back(getEncodedComdatSelectionKind(*C)); 588 size_t Size = C->getName().size(); 589 assert(isUInt<32>(Size)); 590 Vals.push_back(Size); 591 for (char Chr : C->getName()) 592 Vals.push_back((unsigned char)Chr); 593 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0); 594 Vals.clear(); 595 } 596 } 597 598 /// Write a record that will eventually hold the word offset of the 599 /// module-level VST. For now the offset is 0, which will be backpatched 600 /// after the real VST is written. Returns the bit offset to backpatch. 601 static uint64_t WriteValueSymbolTableForwardDecl(BitstreamWriter &Stream) { 602 // Write a placeholder value in for the offset of the real VST, 603 // which is written after the function blocks so that it can include 604 // the offset of each function. The placeholder offset will be 605 // updated when the real VST is written. 606 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 607 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET)); 608 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to 609 // hold the real VST offset. Must use fixed instead of VBR as we don't 610 // know how many VBR chunks to reserve ahead of time. 611 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 612 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(Abbv); 613 614 // Emit the placeholder 615 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0}; 616 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals); 617 618 // Compute and return the bit offset to the placeholder, which will be 619 // patched when the real VST is written. We can simply subtract the 32-bit 620 // fixed size from the current bit number to get the location to backpatch. 621 return Stream.GetCurrentBitNo() - 32; 622 } 623 624 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 }; 625 626 /// Determine the encoding to use for the given string name and length. 627 static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) { 628 bool isChar6 = true; 629 for (const char *C = Str, *E = C + StrLen; C != E; ++C) { 630 if (isChar6) 631 isChar6 = BitCodeAbbrevOp::isChar6(*C); 632 if ((unsigned char)*C & 128) 633 // don't bother scanning the rest. 634 return SE_Fixed8; 635 } 636 if (isChar6) 637 return SE_Char6; 638 else 639 return SE_Fixed7; 640 } 641 642 /// Emit top-level description of module, including target triple, inline asm, 643 /// descriptors for global variables, and function prototype info. 644 /// Returns the bit offset to backpatch with the location of the real VST. 645 static uint64_t WriteModuleInfo(const Module *M, const ValueEnumerator &VE, 646 BitstreamWriter &Stream) { 647 // Emit various pieces of data attached to a module. 648 if (!M->getTargetTriple().empty()) 649 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(), 650 0/*TODO*/, Stream); 651 const std::string &DL = M->getDataLayoutStr(); 652 if (!DL.empty()) 653 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream); 654 if (!M->getModuleInlineAsm().empty()) 655 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(), 656 0/*TODO*/, Stream); 657 658 // Emit information about sections and GC, computing how many there are. Also 659 // compute the maximum alignment value. 660 std::map<std::string, unsigned> SectionMap; 661 std::map<std::string, unsigned> GCMap; 662 unsigned MaxAlignment = 0; 663 unsigned MaxGlobalType = 0; 664 for (const GlobalValue &GV : M->globals()) { 665 MaxAlignment = std::max(MaxAlignment, GV.getAlignment()); 666 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType())); 667 if (GV.hasSection()) { 668 // Give section names unique ID's. 669 unsigned &Entry = SectionMap[GV.getSection()]; 670 if (!Entry) { 671 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(), 672 0/*TODO*/, Stream); 673 Entry = SectionMap.size(); 674 } 675 } 676 } 677 for (const Function &F : *M) { 678 MaxAlignment = std::max(MaxAlignment, F.getAlignment()); 679 if (F.hasSection()) { 680 // Give section names unique ID's. 681 unsigned &Entry = SectionMap[F.getSection()]; 682 if (!Entry) { 683 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(), 684 0/*TODO*/, Stream); 685 Entry = SectionMap.size(); 686 } 687 } 688 if (F.hasGC()) { 689 // Same for GC names. 690 unsigned &Entry = GCMap[F.getGC()]; 691 if (!Entry) { 692 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(), 693 0/*TODO*/, Stream); 694 Entry = GCMap.size(); 695 } 696 } 697 } 698 699 // Emit abbrev for globals, now that we know # sections and max alignment. 700 unsigned SimpleGVarAbbrev = 0; 701 if (!M->global_empty()) { 702 // Add an abbrev for common globals with no visibility or thread localness. 703 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 704 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 705 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 706 Log2_32_Ceil(MaxGlobalType+1))); 707 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2 708 //| explicitType << 1 709 //| constant 710 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 711 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage. 712 if (MaxAlignment == 0) // Alignment. 713 Abbv->Add(BitCodeAbbrevOp(0)); 714 else { 715 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1; 716 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 717 Log2_32_Ceil(MaxEncAlignment+1))); 718 } 719 if (SectionMap.empty()) // Section. 720 Abbv->Add(BitCodeAbbrevOp(0)); 721 else 722 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 723 Log2_32_Ceil(SectionMap.size()+1))); 724 // Don't bother emitting vis + thread local. 725 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv); 726 } 727 728 // Emit the global variable information. 729 SmallVector<unsigned, 64> Vals; 730 for (const GlobalVariable &GV : M->globals()) { 731 unsigned AbbrevToUse = 0; 732 733 // GLOBALVAR: [type, isconst, initid, 734 // linkage, alignment, section, visibility, threadlocal, 735 // unnamed_addr, externally_initialized, dllstorageclass, 736 // comdat] 737 Vals.push_back(VE.getTypeID(GV.getValueType())); 738 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant()); 739 Vals.push_back(GV.isDeclaration() ? 0 : 740 (VE.getValueID(GV.getInitializer()) + 1)); 741 Vals.push_back(getEncodedLinkage(GV)); 742 Vals.push_back(Log2_32(GV.getAlignment())+1); 743 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0); 744 if (GV.isThreadLocal() || 745 GV.getVisibility() != GlobalValue::DefaultVisibility || 746 GV.hasUnnamedAddr() || GV.isExternallyInitialized() || 747 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass || 748 GV.hasComdat()) { 749 Vals.push_back(getEncodedVisibility(GV)); 750 Vals.push_back(getEncodedThreadLocalMode(GV)); 751 Vals.push_back(GV.hasUnnamedAddr()); 752 Vals.push_back(GV.isExternallyInitialized()); 753 Vals.push_back(getEncodedDLLStorageClass(GV)); 754 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0); 755 } else { 756 AbbrevToUse = SimpleGVarAbbrev; 757 } 758 759 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 760 Vals.clear(); 761 } 762 763 // Emit the function proto information. 764 for (const Function &F : *M) { 765 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment, 766 // section, visibility, gc, unnamed_addr, prologuedata, 767 // dllstorageclass, comdat, prefixdata, personalityfn] 768 Vals.push_back(VE.getTypeID(F.getFunctionType())); 769 Vals.push_back(F.getCallingConv()); 770 Vals.push_back(F.isDeclaration()); 771 Vals.push_back(getEncodedLinkage(F)); 772 Vals.push_back(VE.getAttributeID(F.getAttributes())); 773 Vals.push_back(Log2_32(F.getAlignment())+1); 774 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0); 775 Vals.push_back(getEncodedVisibility(F)); 776 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0); 777 Vals.push_back(F.hasUnnamedAddr()); 778 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1) 779 : 0); 780 Vals.push_back(getEncodedDLLStorageClass(F)); 781 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0); 782 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1) 783 : 0); 784 Vals.push_back( 785 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0); 786 787 unsigned AbbrevToUse = 0; 788 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 789 Vals.clear(); 790 } 791 792 // Emit the alias information. 793 for (const GlobalAlias &A : M->aliases()) { 794 // ALIAS: [alias type, aliasee val#, linkage, visibility] 795 Vals.push_back(VE.getTypeID(A.getValueType())); 796 Vals.push_back(A.getType()->getAddressSpace()); 797 Vals.push_back(VE.getValueID(A.getAliasee())); 798 Vals.push_back(getEncodedLinkage(A)); 799 Vals.push_back(getEncodedVisibility(A)); 800 Vals.push_back(getEncodedDLLStorageClass(A)); 801 Vals.push_back(getEncodedThreadLocalMode(A)); 802 Vals.push_back(A.hasUnnamedAddr()); 803 unsigned AbbrevToUse = 0; 804 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse); 805 Vals.clear(); 806 } 807 808 // Emit the module's source file name. 809 { 810 StringEncoding Bits = getStringEncoding(M->getSourceFileName().data(), 811 M->getSourceFileName().size()); 812 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8); 813 if (Bits == SE_Char6) 814 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6); 815 else if (Bits == SE_Fixed7) 816 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7); 817 818 // MODULE_CODE_SOURCE_FILENAME: [namechar x N] 819 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 820 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME)); 821 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 822 Abbv->Add(AbbrevOpToUse); 823 unsigned FilenameAbbrev = Stream.EmitAbbrev(Abbv); 824 825 for (const auto P : M->getSourceFileName()) 826 Vals.push_back((unsigned char)P); 827 828 // Emit the finished record. 829 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev); 830 Vals.clear(); 831 } 832 833 // If we have a VST, write the VSTOFFSET record placeholder and return 834 // its offset. 835 if (M->getValueSymbolTable().empty()) 836 return 0; 837 return WriteValueSymbolTableForwardDecl(Stream); 838 } 839 840 static uint64_t GetOptimizationFlags(const Value *V) { 841 uint64_t Flags = 0; 842 843 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) { 844 if (OBO->hasNoSignedWrap()) 845 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP; 846 if (OBO->hasNoUnsignedWrap()) 847 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP; 848 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) { 849 if (PEO->isExact()) 850 Flags |= 1 << bitc::PEO_EXACT; 851 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) { 852 if (FPMO->hasUnsafeAlgebra()) 853 Flags |= FastMathFlags::UnsafeAlgebra; 854 if (FPMO->hasNoNaNs()) 855 Flags |= FastMathFlags::NoNaNs; 856 if (FPMO->hasNoInfs()) 857 Flags |= FastMathFlags::NoInfs; 858 if (FPMO->hasNoSignedZeros()) 859 Flags |= FastMathFlags::NoSignedZeros; 860 if (FPMO->hasAllowReciprocal()) 861 Flags |= FastMathFlags::AllowReciprocal; 862 } 863 864 return Flags; 865 } 866 867 static void writeValueAsMetadata(const ValueAsMetadata *MD, 868 const ValueEnumerator &VE, 869 BitstreamWriter &Stream, 870 SmallVectorImpl<uint64_t> &Record) { 871 // Mimic an MDNode with a value as one operand. 872 Value *V = MD->getValue(); 873 Record.push_back(VE.getTypeID(V->getType())); 874 Record.push_back(VE.getValueID(V)); 875 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0); 876 Record.clear(); 877 } 878 879 static void writeMDTuple(const MDTuple *N, const ValueEnumerator &VE, 880 BitstreamWriter &Stream, 881 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) { 882 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 883 Metadata *MD = N->getOperand(i); 884 assert(!(MD && isa<LocalAsMetadata>(MD)) && 885 "Unexpected function-local metadata"); 886 Record.push_back(VE.getMetadataOrNullID(MD)); 887 } 888 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE 889 : bitc::METADATA_NODE, 890 Record, Abbrev); 891 Record.clear(); 892 } 893 894 static unsigned createDILocationAbbrev(BitstreamWriter &Stream) { 895 // Assume the column is usually under 128, and always output the inlined-at 896 // location (it's never more expensive than building an array size 1). 897 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 898 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION)); 899 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 900 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 901 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 902 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 903 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 904 return Stream.EmitAbbrev(Abbv); 905 } 906 907 static void writeDILocation(const DILocation *N, const ValueEnumerator &VE, 908 BitstreamWriter &Stream, 909 SmallVectorImpl<uint64_t> &Record, 910 unsigned &Abbrev) { 911 if (!Abbrev) 912 Abbrev = createDILocationAbbrev(Stream); 913 914 Record.push_back(N->isDistinct()); 915 Record.push_back(N->getLine()); 916 Record.push_back(N->getColumn()); 917 Record.push_back(VE.getMetadataID(N->getScope())); 918 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt())); 919 920 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev); 921 Record.clear(); 922 } 923 924 static unsigned createGenericDINodeAbbrev(BitstreamWriter &Stream) { 925 // Assume the column is usually under 128, and always output the inlined-at 926 // location (it's never more expensive than building an array size 1). 927 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 928 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG)); 929 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 930 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 931 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 932 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 933 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 934 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 935 return Stream.EmitAbbrev(Abbv); 936 } 937 938 static void writeGenericDINode(const GenericDINode *N, 939 const ValueEnumerator &VE, 940 BitstreamWriter &Stream, 941 SmallVectorImpl<uint64_t> &Record, 942 unsigned &Abbrev) { 943 if (!Abbrev) 944 Abbrev = createGenericDINodeAbbrev(Stream); 945 946 Record.push_back(N->isDistinct()); 947 Record.push_back(N->getTag()); 948 Record.push_back(0); // Per-tag version field; unused for now. 949 950 for (auto &I : N->operands()) 951 Record.push_back(VE.getMetadataOrNullID(I)); 952 953 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev); 954 Record.clear(); 955 } 956 957 static uint64_t rotateSign(int64_t I) { 958 uint64_t U = I; 959 return I < 0 ? ~(U << 1) : U << 1; 960 } 961 962 static void writeDISubrange(const DISubrange *N, const ValueEnumerator &, 963 BitstreamWriter &Stream, 964 SmallVectorImpl<uint64_t> &Record, 965 unsigned Abbrev) { 966 Record.push_back(N->isDistinct()); 967 Record.push_back(N->getCount()); 968 Record.push_back(rotateSign(N->getLowerBound())); 969 970 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev); 971 Record.clear(); 972 } 973 974 static void writeDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE, 975 BitstreamWriter &Stream, 976 SmallVectorImpl<uint64_t> &Record, 977 unsigned Abbrev) { 978 Record.push_back(N->isDistinct()); 979 Record.push_back(rotateSign(N->getValue())); 980 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 981 982 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev); 983 Record.clear(); 984 } 985 986 static void writeDIBasicType(const DIBasicType *N, const ValueEnumerator &VE, 987 BitstreamWriter &Stream, 988 SmallVectorImpl<uint64_t> &Record, 989 unsigned Abbrev) { 990 Record.push_back(N->isDistinct()); 991 Record.push_back(N->getTag()); 992 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 993 Record.push_back(N->getSizeInBits()); 994 Record.push_back(N->getAlignInBits()); 995 Record.push_back(N->getEncoding()); 996 997 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev); 998 Record.clear(); 999 } 1000 1001 static void writeDIDerivedType(const DIDerivedType *N, 1002 const ValueEnumerator &VE, 1003 BitstreamWriter &Stream, 1004 SmallVectorImpl<uint64_t> &Record, 1005 unsigned Abbrev) { 1006 Record.push_back(N->isDistinct()); 1007 Record.push_back(N->getTag()); 1008 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1009 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1010 Record.push_back(N->getLine()); 1011 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1012 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1013 Record.push_back(N->getSizeInBits()); 1014 Record.push_back(N->getAlignInBits()); 1015 Record.push_back(N->getOffsetInBits()); 1016 Record.push_back(N->getFlags()); 1017 Record.push_back(VE.getMetadataOrNullID(N->getExtraData())); 1018 1019 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev); 1020 Record.clear(); 1021 } 1022 1023 static void writeDICompositeType(const DICompositeType *N, 1024 const ValueEnumerator &VE, 1025 BitstreamWriter &Stream, 1026 SmallVectorImpl<uint64_t> &Record, 1027 unsigned Abbrev) { 1028 Record.push_back(N->isDistinct()); 1029 Record.push_back(N->getTag()); 1030 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1031 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1032 Record.push_back(N->getLine()); 1033 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1034 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1035 Record.push_back(N->getSizeInBits()); 1036 Record.push_back(N->getAlignInBits()); 1037 Record.push_back(N->getOffsetInBits()); 1038 Record.push_back(N->getFlags()); 1039 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 1040 Record.push_back(N->getRuntimeLang()); 1041 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder())); 1042 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1043 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier())); 1044 1045 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev); 1046 Record.clear(); 1047 } 1048 1049 static void writeDISubroutineType(const DISubroutineType *N, 1050 const ValueEnumerator &VE, 1051 BitstreamWriter &Stream, 1052 SmallVectorImpl<uint64_t> &Record, 1053 unsigned Abbrev) { 1054 Record.push_back(N->isDistinct()); 1055 Record.push_back(N->getFlags()); 1056 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get())); 1057 1058 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev); 1059 Record.clear(); 1060 } 1061 1062 static void writeDIFile(const DIFile *N, const ValueEnumerator &VE, 1063 BitstreamWriter &Stream, 1064 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) { 1065 Record.push_back(N->isDistinct()); 1066 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename())); 1067 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory())); 1068 1069 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev); 1070 Record.clear(); 1071 } 1072 1073 static void writeDICompileUnit(const DICompileUnit *N, 1074 const ValueEnumerator &VE, 1075 BitstreamWriter &Stream, 1076 SmallVectorImpl<uint64_t> &Record, 1077 unsigned Abbrev) { 1078 assert(N->isDistinct() && "Expected distinct compile units"); 1079 Record.push_back(/* IsDistinct */ true); 1080 Record.push_back(N->getSourceLanguage()); 1081 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1082 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer())); 1083 Record.push_back(N->isOptimized()); 1084 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags())); 1085 Record.push_back(N->getRuntimeVersion()); 1086 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename())); 1087 Record.push_back(N->getEmissionKind()); 1088 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get())); 1089 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get())); 1090 Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get())); 1091 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get())); 1092 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get())); 1093 Record.push_back(N->getDWOId()); 1094 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get())); 1095 1096 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev); 1097 Record.clear(); 1098 } 1099 1100 static void writeDISubprogram(const DISubprogram *N, const ValueEnumerator &VE, 1101 BitstreamWriter &Stream, 1102 SmallVectorImpl<uint64_t> &Record, 1103 unsigned Abbrev) { 1104 Record.push_back(N->isDistinct()); 1105 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1106 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1107 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1108 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1109 Record.push_back(N->getLine()); 1110 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1111 Record.push_back(N->isLocalToUnit()); 1112 Record.push_back(N->isDefinition()); 1113 Record.push_back(N->getScopeLine()); 1114 Record.push_back(VE.getMetadataOrNullID(N->getContainingType())); 1115 Record.push_back(N->getVirtuality()); 1116 Record.push_back(N->getVirtualIndex()); 1117 Record.push_back(N->getFlags()); 1118 Record.push_back(N->isOptimized()); 1119 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1120 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration())); 1121 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get())); 1122 1123 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev); 1124 Record.clear(); 1125 } 1126 1127 static void writeDILexicalBlock(const DILexicalBlock *N, 1128 const ValueEnumerator &VE, 1129 BitstreamWriter &Stream, 1130 SmallVectorImpl<uint64_t> &Record, 1131 unsigned Abbrev) { 1132 Record.push_back(N->isDistinct()); 1133 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1134 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1135 Record.push_back(N->getLine()); 1136 Record.push_back(N->getColumn()); 1137 1138 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev); 1139 Record.clear(); 1140 } 1141 1142 static void writeDILexicalBlockFile(const DILexicalBlockFile *N, 1143 const ValueEnumerator &VE, 1144 BitstreamWriter &Stream, 1145 SmallVectorImpl<uint64_t> &Record, 1146 unsigned Abbrev) { 1147 Record.push_back(N->isDistinct()); 1148 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1149 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1150 Record.push_back(N->getDiscriminator()); 1151 1152 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev); 1153 Record.clear(); 1154 } 1155 1156 static void writeDINamespace(const DINamespace *N, const ValueEnumerator &VE, 1157 BitstreamWriter &Stream, 1158 SmallVectorImpl<uint64_t> &Record, 1159 unsigned Abbrev) { 1160 Record.push_back(N->isDistinct()); 1161 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1162 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1163 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1164 Record.push_back(N->getLine()); 1165 1166 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev); 1167 Record.clear(); 1168 } 1169 1170 static void writeDIMacro(const DIMacro *N, const ValueEnumerator &VE, 1171 BitstreamWriter &Stream, 1172 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) { 1173 Record.push_back(N->isDistinct()); 1174 Record.push_back(N->getMacinfoType()); 1175 Record.push_back(N->getLine()); 1176 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1177 Record.push_back(VE.getMetadataOrNullID(N->getRawValue())); 1178 1179 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev); 1180 Record.clear(); 1181 } 1182 1183 static void writeDIMacroFile(const DIMacroFile *N, const ValueEnumerator &VE, 1184 BitstreamWriter &Stream, 1185 SmallVectorImpl<uint64_t> &Record, 1186 unsigned Abbrev) { 1187 Record.push_back(N->isDistinct()); 1188 Record.push_back(N->getMacinfoType()); 1189 Record.push_back(N->getLine()); 1190 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1191 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 1192 1193 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev); 1194 Record.clear(); 1195 } 1196 1197 static void writeDIModule(const DIModule *N, const ValueEnumerator &VE, 1198 BitstreamWriter &Stream, 1199 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) { 1200 Record.push_back(N->isDistinct()); 1201 for (auto &I : N->operands()) 1202 Record.push_back(VE.getMetadataOrNullID(I)); 1203 1204 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev); 1205 Record.clear(); 1206 } 1207 1208 static void writeDITemplateTypeParameter(const DITemplateTypeParameter *N, 1209 const ValueEnumerator &VE, 1210 BitstreamWriter &Stream, 1211 SmallVectorImpl<uint64_t> &Record, 1212 unsigned Abbrev) { 1213 Record.push_back(N->isDistinct()); 1214 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1215 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1216 1217 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev); 1218 Record.clear(); 1219 } 1220 1221 static void writeDITemplateValueParameter(const DITemplateValueParameter *N, 1222 const ValueEnumerator &VE, 1223 BitstreamWriter &Stream, 1224 SmallVectorImpl<uint64_t> &Record, 1225 unsigned Abbrev) { 1226 Record.push_back(N->isDistinct()); 1227 Record.push_back(N->getTag()); 1228 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1229 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1230 Record.push_back(VE.getMetadataOrNullID(N->getValue())); 1231 1232 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev); 1233 Record.clear(); 1234 } 1235 1236 static void writeDIGlobalVariable(const DIGlobalVariable *N, 1237 const ValueEnumerator &VE, 1238 BitstreamWriter &Stream, 1239 SmallVectorImpl<uint64_t> &Record, 1240 unsigned Abbrev) { 1241 Record.push_back(N->isDistinct()); 1242 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1243 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1244 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1245 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1246 Record.push_back(N->getLine()); 1247 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1248 Record.push_back(N->isLocalToUnit()); 1249 Record.push_back(N->isDefinition()); 1250 Record.push_back(VE.getMetadataOrNullID(N->getRawVariable())); 1251 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration())); 1252 1253 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev); 1254 Record.clear(); 1255 } 1256 1257 static void writeDILocalVariable(const DILocalVariable *N, 1258 const ValueEnumerator &VE, 1259 BitstreamWriter &Stream, 1260 SmallVectorImpl<uint64_t> &Record, 1261 unsigned Abbrev) { 1262 Record.push_back(N->isDistinct()); 1263 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1264 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1265 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1266 Record.push_back(N->getLine()); 1267 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1268 Record.push_back(N->getArg()); 1269 Record.push_back(N->getFlags()); 1270 1271 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev); 1272 Record.clear(); 1273 } 1274 1275 static void writeDIExpression(const DIExpression *N, const ValueEnumerator &, 1276 BitstreamWriter &Stream, 1277 SmallVectorImpl<uint64_t> &Record, 1278 unsigned Abbrev) { 1279 Record.reserve(N->getElements().size() + 1); 1280 1281 Record.push_back(N->isDistinct()); 1282 Record.append(N->elements_begin(), N->elements_end()); 1283 1284 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev); 1285 Record.clear(); 1286 } 1287 1288 static void writeDIObjCProperty(const DIObjCProperty *N, 1289 const ValueEnumerator &VE, 1290 BitstreamWriter &Stream, 1291 SmallVectorImpl<uint64_t> &Record, 1292 unsigned Abbrev) { 1293 Record.push_back(N->isDistinct()); 1294 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1295 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1296 Record.push_back(N->getLine()); 1297 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName())); 1298 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName())); 1299 Record.push_back(N->getAttributes()); 1300 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1301 1302 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev); 1303 Record.clear(); 1304 } 1305 1306 static void writeDIImportedEntity(const DIImportedEntity *N, 1307 const ValueEnumerator &VE, 1308 BitstreamWriter &Stream, 1309 SmallVectorImpl<uint64_t> &Record, 1310 unsigned Abbrev) { 1311 Record.push_back(N->isDistinct()); 1312 Record.push_back(N->getTag()); 1313 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1314 Record.push_back(VE.getMetadataOrNullID(N->getEntity())); 1315 Record.push_back(N->getLine()); 1316 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1317 1318 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev); 1319 Record.clear(); 1320 } 1321 1322 static unsigned createNamedMetadataAbbrev(BitstreamWriter &Stream) { 1323 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1324 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME)); 1325 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1326 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1327 return Stream.EmitAbbrev(Abbv); 1328 } 1329 1330 static void writeNamedMetadata(const Module &M, const ValueEnumerator &VE, 1331 BitstreamWriter &Stream, 1332 SmallVectorImpl<uint64_t> &Record) { 1333 if (M.named_metadata_empty()) 1334 return; 1335 1336 unsigned Abbrev = createNamedMetadataAbbrev(Stream); 1337 for (const NamedMDNode &NMD : M.named_metadata()) { 1338 // Write name. 1339 StringRef Str = NMD.getName(); 1340 Record.append(Str.bytes_begin(), Str.bytes_end()); 1341 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev); 1342 Record.clear(); 1343 1344 // Write named metadata operands. 1345 for (const MDNode *N : NMD.operands()) 1346 Record.push_back(VE.getMetadataID(N)); 1347 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0); 1348 Record.clear(); 1349 } 1350 } 1351 1352 static unsigned createMetadataStringsAbbrev(BitstreamWriter &Stream) { 1353 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1354 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS)); 1355 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings 1356 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars 1357 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1358 return Stream.EmitAbbrev(Abbv); 1359 } 1360 1361 /// Write out a record for MDString. 1362 /// 1363 /// All the metadata strings in a metadata block are emitted in a single 1364 /// record. The sizes and strings themselves are shoved into a blob. 1365 static void writeMetadataStrings(ArrayRef<const Metadata *> Strings, 1366 BitstreamWriter &Stream, 1367 SmallVectorImpl<uint64_t> &Record) { 1368 if (Strings.empty()) 1369 return; 1370 1371 // Start the record with the number of strings. 1372 Record.push_back(bitc::METADATA_STRINGS); 1373 Record.push_back(Strings.size()); 1374 1375 // Emit the sizes of the strings in the blob. 1376 SmallString<256> Blob; 1377 { 1378 BitstreamWriter W(Blob); 1379 for (const Metadata *MD : Strings) 1380 W.EmitVBR(cast<MDString>(MD)->getLength(), 6); 1381 W.FlushToWord(); 1382 } 1383 1384 // Add the offset to the strings to the record. 1385 Record.push_back(Blob.size()); 1386 1387 // Add the strings to the blob. 1388 for (const Metadata *MD : Strings) 1389 Blob.append(cast<MDString>(MD)->getString()); 1390 1391 // Emit the final record. 1392 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(Stream), Record, Blob); 1393 Record.clear(); 1394 } 1395 1396 static void writeMetadataRecords(ArrayRef<const Metadata *> MDs, 1397 const ValueEnumerator &VE, 1398 BitstreamWriter &Stream, 1399 SmallVectorImpl<uint64_t> &Record) { 1400 if (MDs.empty()) 1401 return; 1402 1403 // Initialize MDNode abbreviations. 1404 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0; 1405 #include "llvm/IR/Metadata.def" 1406 1407 for (const Metadata *MD : MDs) { 1408 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 1409 assert(N->isResolved() && "Expected forward references to be resolved"); 1410 1411 switch (N->getMetadataID()) { 1412 default: 1413 llvm_unreachable("Invalid MDNode subclass"); 1414 #define HANDLE_MDNODE_LEAF(CLASS) \ 1415 case Metadata::CLASS##Kind: \ 1416 write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \ 1417 continue; 1418 #include "llvm/IR/Metadata.def" 1419 } 1420 } 1421 writeValueAsMetadata(cast<ValueAsMetadata>(MD), VE, Stream, Record); 1422 } 1423 } 1424 1425 static void writeModuleMetadata(const Module &M, 1426 const ValueEnumerator &VE, 1427 BitstreamWriter &Stream) { 1428 if (VE.getMDs().empty() && M.named_metadata_empty()) 1429 return; 1430 1431 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 1432 SmallVector<uint64_t, 64> Record; 1433 writeMetadataStrings(VE.getMDStrings(), Stream, Record); 1434 writeMetadataRecords(VE.getNonMDStrings(), VE, Stream, Record); 1435 writeNamedMetadata(M, VE, Stream, Record); 1436 Stream.ExitBlock(); 1437 } 1438 1439 static void writeFunctionMetadata(const Function &F, const ValueEnumerator &VE, 1440 BitstreamWriter &Stream) { 1441 ArrayRef<const Metadata *> MDs = VE.getFunctionMDs(); 1442 if (MDs.empty()) 1443 return; 1444 1445 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 1446 SmallVector<uint64_t, 64> Record; 1447 writeMetadataRecords(MDs, VE, Stream, Record); 1448 Stream.ExitBlock(); 1449 } 1450 1451 static void WriteMetadataAttachment(const Function &F, 1452 const ValueEnumerator &VE, 1453 BitstreamWriter &Stream) { 1454 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); 1455 1456 SmallVector<uint64_t, 64> Record; 1457 1458 // Write metadata attachments 1459 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] 1460 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 1461 F.getAllMetadata(MDs); 1462 if (!MDs.empty()) { 1463 for (const auto &I : MDs) { 1464 Record.push_back(I.first); 1465 Record.push_back(VE.getMetadataID(I.second)); 1466 } 1467 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 1468 Record.clear(); 1469 } 1470 1471 for (const BasicBlock &BB : F) 1472 for (const Instruction &I : BB) { 1473 MDs.clear(); 1474 I.getAllMetadataOtherThanDebugLoc(MDs); 1475 1476 // If no metadata, ignore instruction. 1477 if (MDs.empty()) continue; 1478 1479 Record.push_back(VE.getInstructionID(&I)); 1480 1481 for (unsigned i = 0, e = MDs.size(); i != e; ++i) { 1482 Record.push_back(MDs[i].first); 1483 Record.push_back(VE.getMetadataID(MDs[i].second)); 1484 } 1485 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 1486 Record.clear(); 1487 } 1488 1489 Stream.ExitBlock(); 1490 } 1491 1492 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) { 1493 SmallVector<uint64_t, 64> Record; 1494 1495 // Write metadata kinds 1496 // METADATA_KIND - [n x [id, name]] 1497 SmallVector<StringRef, 8> Names; 1498 M->getMDKindNames(Names); 1499 1500 if (Names.empty()) return; 1501 1502 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3); 1503 1504 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) { 1505 Record.push_back(MDKindID); 1506 StringRef KName = Names[MDKindID]; 1507 Record.append(KName.begin(), KName.end()); 1508 1509 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); 1510 Record.clear(); 1511 } 1512 1513 Stream.ExitBlock(); 1514 } 1515 1516 static void WriteOperandBundleTags(const Module *M, BitstreamWriter &Stream) { 1517 // Write metadata kinds 1518 // 1519 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG 1520 // 1521 // OPERAND_BUNDLE_TAG - [strchr x N] 1522 1523 SmallVector<StringRef, 8> Tags; 1524 M->getOperandBundleTags(Tags); 1525 1526 if (Tags.empty()) 1527 return; 1528 1529 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3); 1530 1531 SmallVector<uint64_t, 64> Record; 1532 1533 for (auto Tag : Tags) { 1534 Record.append(Tag.begin(), Tag.end()); 1535 1536 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0); 1537 Record.clear(); 1538 } 1539 1540 Stream.ExitBlock(); 1541 } 1542 1543 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) { 1544 if ((int64_t)V >= 0) 1545 Vals.push_back(V << 1); 1546 else 1547 Vals.push_back((-V << 1) | 1); 1548 } 1549 1550 static void WriteConstants(unsigned FirstVal, unsigned LastVal, 1551 const ValueEnumerator &VE, 1552 BitstreamWriter &Stream, bool isGlobal) { 1553 if (FirstVal == LastVal) return; 1554 1555 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); 1556 1557 unsigned AggregateAbbrev = 0; 1558 unsigned String8Abbrev = 0; 1559 unsigned CString7Abbrev = 0; 1560 unsigned CString6Abbrev = 0; 1561 // If this is a constant pool for the module, emit module-specific abbrevs. 1562 if (isGlobal) { 1563 // Abbrev for CST_CODE_AGGREGATE. 1564 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1565 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE)); 1566 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1567 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1))); 1568 AggregateAbbrev = Stream.EmitAbbrev(Abbv); 1569 1570 // Abbrev for CST_CODE_STRING. 1571 Abbv = new BitCodeAbbrev(); 1572 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING)); 1573 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1574 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1575 String8Abbrev = Stream.EmitAbbrev(Abbv); 1576 // Abbrev for CST_CODE_CSTRING. 1577 Abbv = new BitCodeAbbrev(); 1578 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 1579 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1580 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 1581 CString7Abbrev = Stream.EmitAbbrev(Abbv); 1582 // Abbrev for CST_CODE_CSTRING. 1583 Abbv = new BitCodeAbbrev(); 1584 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 1585 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1586 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1587 CString6Abbrev = Stream.EmitAbbrev(Abbv); 1588 } 1589 1590 SmallVector<uint64_t, 64> Record; 1591 1592 const ValueEnumerator::ValueList &Vals = VE.getValues(); 1593 Type *LastTy = nullptr; 1594 for (unsigned i = FirstVal; i != LastVal; ++i) { 1595 const Value *V = Vals[i].first; 1596 // If we need to switch types, do so now. 1597 if (V->getType() != LastTy) { 1598 LastTy = V->getType(); 1599 Record.push_back(VE.getTypeID(LastTy)); 1600 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record, 1601 CONSTANTS_SETTYPE_ABBREV); 1602 Record.clear(); 1603 } 1604 1605 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 1606 Record.push_back(unsigned(IA->hasSideEffects()) | 1607 unsigned(IA->isAlignStack()) << 1 | 1608 unsigned(IA->getDialect()&1) << 2); 1609 1610 // Add the asm string. 1611 const std::string &AsmStr = IA->getAsmString(); 1612 Record.push_back(AsmStr.size()); 1613 Record.append(AsmStr.begin(), AsmStr.end()); 1614 1615 // Add the constraint string. 1616 const std::string &ConstraintStr = IA->getConstraintString(); 1617 Record.push_back(ConstraintStr.size()); 1618 Record.append(ConstraintStr.begin(), ConstraintStr.end()); 1619 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record); 1620 Record.clear(); 1621 continue; 1622 } 1623 const Constant *C = cast<Constant>(V); 1624 unsigned Code = -1U; 1625 unsigned AbbrevToUse = 0; 1626 if (C->isNullValue()) { 1627 Code = bitc::CST_CODE_NULL; 1628 } else if (isa<UndefValue>(C)) { 1629 Code = bitc::CST_CODE_UNDEF; 1630 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 1631 if (IV->getBitWidth() <= 64) { 1632 uint64_t V = IV->getSExtValue(); 1633 emitSignedInt64(Record, V); 1634 Code = bitc::CST_CODE_INTEGER; 1635 AbbrevToUse = CONSTANTS_INTEGER_ABBREV; 1636 } else { // Wide integers, > 64 bits in size. 1637 // We have an arbitrary precision integer value to write whose 1638 // bit width is > 64. However, in canonical unsigned integer 1639 // format it is likely that the high bits are going to be zero. 1640 // So, we only write the number of active words. 1641 unsigned NWords = IV->getValue().getActiveWords(); 1642 const uint64_t *RawWords = IV->getValue().getRawData(); 1643 for (unsigned i = 0; i != NWords; ++i) { 1644 emitSignedInt64(Record, RawWords[i]); 1645 } 1646 Code = bitc::CST_CODE_WIDE_INTEGER; 1647 } 1648 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 1649 Code = bitc::CST_CODE_FLOAT; 1650 Type *Ty = CFP->getType(); 1651 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) { 1652 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue()); 1653 } else if (Ty->isX86_FP80Ty()) { 1654 // api needed to prevent premature destruction 1655 // bits are not in the same order as a normal i80 APInt, compensate. 1656 APInt api = CFP->getValueAPF().bitcastToAPInt(); 1657 const uint64_t *p = api.getRawData(); 1658 Record.push_back((p[1] << 48) | (p[0] >> 16)); 1659 Record.push_back(p[0] & 0xffffLL); 1660 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) { 1661 APInt api = CFP->getValueAPF().bitcastToAPInt(); 1662 const uint64_t *p = api.getRawData(); 1663 Record.push_back(p[0]); 1664 Record.push_back(p[1]); 1665 } else { 1666 assert (0 && "Unknown FP type!"); 1667 } 1668 } else if (isa<ConstantDataSequential>(C) && 1669 cast<ConstantDataSequential>(C)->isString()) { 1670 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C); 1671 // Emit constant strings specially. 1672 unsigned NumElts = Str->getNumElements(); 1673 // If this is a null-terminated string, use the denser CSTRING encoding. 1674 if (Str->isCString()) { 1675 Code = bitc::CST_CODE_CSTRING; 1676 --NumElts; // Don't encode the null, which isn't allowed by char6. 1677 } else { 1678 Code = bitc::CST_CODE_STRING; 1679 AbbrevToUse = String8Abbrev; 1680 } 1681 bool isCStr7 = Code == bitc::CST_CODE_CSTRING; 1682 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; 1683 for (unsigned i = 0; i != NumElts; ++i) { 1684 unsigned char V = Str->getElementAsInteger(i); 1685 Record.push_back(V); 1686 isCStr7 &= (V & 128) == 0; 1687 if (isCStrChar6) 1688 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 1689 } 1690 1691 if (isCStrChar6) 1692 AbbrevToUse = CString6Abbrev; 1693 else if (isCStr7) 1694 AbbrevToUse = CString7Abbrev; 1695 } else if (const ConstantDataSequential *CDS = 1696 dyn_cast<ConstantDataSequential>(C)) { 1697 Code = bitc::CST_CODE_DATA; 1698 Type *EltTy = CDS->getType()->getElementType(); 1699 if (isa<IntegerType>(EltTy)) { 1700 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 1701 Record.push_back(CDS->getElementAsInteger(i)); 1702 } else { 1703 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 1704 Record.push_back( 1705 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue()); 1706 } 1707 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) || 1708 isa<ConstantVector>(C)) { 1709 Code = bitc::CST_CODE_AGGREGATE; 1710 for (const Value *Op : C->operands()) 1711 Record.push_back(VE.getValueID(Op)); 1712 AbbrevToUse = AggregateAbbrev; 1713 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1714 switch (CE->getOpcode()) { 1715 default: 1716 if (Instruction::isCast(CE->getOpcode())) { 1717 Code = bitc::CST_CODE_CE_CAST; 1718 Record.push_back(GetEncodedCastOpcode(CE->getOpcode())); 1719 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 1720 Record.push_back(VE.getValueID(C->getOperand(0))); 1721 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev; 1722 } else { 1723 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 1724 Code = bitc::CST_CODE_CE_BINOP; 1725 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode())); 1726 Record.push_back(VE.getValueID(C->getOperand(0))); 1727 Record.push_back(VE.getValueID(C->getOperand(1))); 1728 uint64_t Flags = GetOptimizationFlags(CE); 1729 if (Flags != 0) 1730 Record.push_back(Flags); 1731 } 1732 break; 1733 case Instruction::GetElementPtr: { 1734 Code = bitc::CST_CODE_CE_GEP; 1735 const auto *GO = cast<GEPOperator>(C); 1736 if (GO->isInBounds()) 1737 Code = bitc::CST_CODE_CE_INBOUNDS_GEP; 1738 Record.push_back(VE.getTypeID(GO->getSourceElementType())); 1739 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 1740 Record.push_back(VE.getTypeID(C->getOperand(i)->getType())); 1741 Record.push_back(VE.getValueID(C->getOperand(i))); 1742 } 1743 break; 1744 } 1745 case Instruction::Select: 1746 Code = bitc::CST_CODE_CE_SELECT; 1747 Record.push_back(VE.getValueID(C->getOperand(0))); 1748 Record.push_back(VE.getValueID(C->getOperand(1))); 1749 Record.push_back(VE.getValueID(C->getOperand(2))); 1750 break; 1751 case Instruction::ExtractElement: 1752 Code = bitc::CST_CODE_CE_EXTRACTELT; 1753 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 1754 Record.push_back(VE.getValueID(C->getOperand(0))); 1755 Record.push_back(VE.getTypeID(C->getOperand(1)->getType())); 1756 Record.push_back(VE.getValueID(C->getOperand(1))); 1757 break; 1758 case Instruction::InsertElement: 1759 Code = bitc::CST_CODE_CE_INSERTELT; 1760 Record.push_back(VE.getValueID(C->getOperand(0))); 1761 Record.push_back(VE.getValueID(C->getOperand(1))); 1762 Record.push_back(VE.getTypeID(C->getOperand(2)->getType())); 1763 Record.push_back(VE.getValueID(C->getOperand(2))); 1764 break; 1765 case Instruction::ShuffleVector: 1766 // If the return type and argument types are the same, this is a 1767 // standard shufflevector instruction. If the types are different, 1768 // then the shuffle is widening or truncating the input vectors, and 1769 // the argument type must also be encoded. 1770 if (C->getType() == C->getOperand(0)->getType()) { 1771 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 1772 } else { 1773 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 1774 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 1775 } 1776 Record.push_back(VE.getValueID(C->getOperand(0))); 1777 Record.push_back(VE.getValueID(C->getOperand(1))); 1778 Record.push_back(VE.getValueID(C->getOperand(2))); 1779 break; 1780 case Instruction::ICmp: 1781 case Instruction::FCmp: 1782 Code = bitc::CST_CODE_CE_CMP; 1783 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 1784 Record.push_back(VE.getValueID(C->getOperand(0))); 1785 Record.push_back(VE.getValueID(C->getOperand(1))); 1786 Record.push_back(CE->getPredicate()); 1787 break; 1788 } 1789 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) { 1790 Code = bitc::CST_CODE_BLOCKADDRESS; 1791 Record.push_back(VE.getTypeID(BA->getFunction()->getType())); 1792 Record.push_back(VE.getValueID(BA->getFunction())); 1793 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock())); 1794 } else { 1795 #ifndef NDEBUG 1796 C->dump(); 1797 #endif 1798 llvm_unreachable("Unknown constant!"); 1799 } 1800 Stream.EmitRecord(Code, Record, AbbrevToUse); 1801 Record.clear(); 1802 } 1803 1804 Stream.ExitBlock(); 1805 } 1806 1807 static void WriteModuleConstants(const ValueEnumerator &VE, 1808 BitstreamWriter &Stream) { 1809 const ValueEnumerator::ValueList &Vals = VE.getValues(); 1810 1811 // Find the first constant to emit, which is the first non-globalvalue value. 1812 // We know globalvalues have been emitted by WriteModuleInfo. 1813 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 1814 if (!isa<GlobalValue>(Vals[i].first)) { 1815 WriteConstants(i, Vals.size(), VE, Stream, true); 1816 return; 1817 } 1818 } 1819 } 1820 1821 /// PushValueAndType - The file has to encode both the value and type id for 1822 /// many values, because we need to know what type to create for forward 1823 /// references. However, most operands are not forward references, so this type 1824 /// field is not needed. 1825 /// 1826 /// This function adds V's value ID to Vals. If the value ID is higher than the 1827 /// instruction ID, then it is a forward reference, and it also includes the 1828 /// type ID. The value ID that is written is encoded relative to the InstID. 1829 static bool PushValueAndType(const Value *V, unsigned InstID, 1830 SmallVectorImpl<unsigned> &Vals, 1831 ValueEnumerator &VE) { 1832 unsigned ValID = VE.getValueID(V); 1833 // Make encoding relative to the InstID. 1834 Vals.push_back(InstID - ValID); 1835 if (ValID >= InstID) { 1836 Vals.push_back(VE.getTypeID(V->getType())); 1837 return true; 1838 } 1839 return false; 1840 } 1841 1842 static void WriteOperandBundles(BitstreamWriter &Stream, ImmutableCallSite CS, 1843 unsigned InstID, ValueEnumerator &VE) { 1844 SmallVector<unsigned, 64> Record; 1845 LLVMContext &C = CS.getInstruction()->getContext(); 1846 1847 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) { 1848 const auto &Bundle = CS.getOperandBundleAt(i); 1849 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName())); 1850 1851 for (auto &Input : Bundle.Inputs) 1852 PushValueAndType(Input, InstID, Record, VE); 1853 1854 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record); 1855 Record.clear(); 1856 } 1857 } 1858 1859 /// pushValue - Like PushValueAndType, but where the type of the value is 1860 /// omitted (perhaps it was already encoded in an earlier operand). 1861 static void pushValue(const Value *V, unsigned InstID, 1862 SmallVectorImpl<unsigned> &Vals, 1863 ValueEnumerator &VE) { 1864 unsigned ValID = VE.getValueID(V); 1865 Vals.push_back(InstID - ValID); 1866 } 1867 1868 static void pushValueSigned(const Value *V, unsigned InstID, 1869 SmallVectorImpl<uint64_t> &Vals, 1870 ValueEnumerator &VE) { 1871 unsigned ValID = VE.getValueID(V); 1872 int64_t diff = ((int32_t)InstID - (int32_t)ValID); 1873 emitSignedInt64(Vals, diff); 1874 } 1875 1876 /// WriteInstruction - Emit an instruction to the specified stream. 1877 static void WriteInstruction(const Instruction &I, unsigned InstID, 1878 ValueEnumerator &VE, BitstreamWriter &Stream, 1879 SmallVectorImpl<unsigned> &Vals) { 1880 unsigned Code = 0; 1881 unsigned AbbrevToUse = 0; 1882 VE.setInstructionID(&I); 1883 switch (I.getOpcode()) { 1884 default: 1885 if (Instruction::isCast(I.getOpcode())) { 1886 Code = bitc::FUNC_CODE_INST_CAST; 1887 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 1888 AbbrevToUse = FUNCTION_INST_CAST_ABBREV; 1889 Vals.push_back(VE.getTypeID(I.getType())); 1890 Vals.push_back(GetEncodedCastOpcode(I.getOpcode())); 1891 } else { 1892 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 1893 Code = bitc::FUNC_CODE_INST_BINOP; 1894 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 1895 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV; 1896 pushValue(I.getOperand(1), InstID, Vals, VE); 1897 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode())); 1898 uint64_t Flags = GetOptimizationFlags(&I); 1899 if (Flags != 0) { 1900 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV) 1901 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV; 1902 Vals.push_back(Flags); 1903 } 1904 } 1905 break; 1906 1907 case Instruction::GetElementPtr: { 1908 Code = bitc::FUNC_CODE_INST_GEP; 1909 AbbrevToUse = FUNCTION_INST_GEP_ABBREV; 1910 auto &GEPInst = cast<GetElementPtrInst>(I); 1911 Vals.push_back(GEPInst.isInBounds()); 1912 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType())); 1913 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 1914 PushValueAndType(I.getOperand(i), InstID, Vals, VE); 1915 break; 1916 } 1917 case Instruction::ExtractValue: { 1918 Code = bitc::FUNC_CODE_INST_EXTRACTVAL; 1919 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1920 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I); 1921 Vals.append(EVI->idx_begin(), EVI->idx_end()); 1922 break; 1923 } 1924 case Instruction::InsertValue: { 1925 Code = bitc::FUNC_CODE_INST_INSERTVAL; 1926 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1927 PushValueAndType(I.getOperand(1), InstID, Vals, VE); 1928 const InsertValueInst *IVI = cast<InsertValueInst>(&I); 1929 Vals.append(IVI->idx_begin(), IVI->idx_end()); 1930 break; 1931 } 1932 case Instruction::Select: 1933 Code = bitc::FUNC_CODE_INST_VSELECT; 1934 PushValueAndType(I.getOperand(1), InstID, Vals, VE); 1935 pushValue(I.getOperand(2), InstID, Vals, VE); 1936 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1937 break; 1938 case Instruction::ExtractElement: 1939 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 1940 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1941 PushValueAndType(I.getOperand(1), InstID, Vals, VE); 1942 break; 1943 case Instruction::InsertElement: 1944 Code = bitc::FUNC_CODE_INST_INSERTELT; 1945 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1946 pushValue(I.getOperand(1), InstID, Vals, VE); 1947 PushValueAndType(I.getOperand(2), InstID, Vals, VE); 1948 break; 1949 case Instruction::ShuffleVector: 1950 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 1951 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1952 pushValue(I.getOperand(1), InstID, Vals, VE); 1953 pushValue(I.getOperand(2), InstID, Vals, VE); 1954 break; 1955 case Instruction::ICmp: 1956 case Instruction::FCmp: { 1957 // compare returning Int1Ty or vector of Int1Ty 1958 Code = bitc::FUNC_CODE_INST_CMP2; 1959 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1960 pushValue(I.getOperand(1), InstID, Vals, VE); 1961 Vals.push_back(cast<CmpInst>(I).getPredicate()); 1962 uint64_t Flags = GetOptimizationFlags(&I); 1963 if (Flags != 0) 1964 Vals.push_back(Flags); 1965 break; 1966 } 1967 1968 case Instruction::Ret: 1969 { 1970 Code = bitc::FUNC_CODE_INST_RET; 1971 unsigned NumOperands = I.getNumOperands(); 1972 if (NumOperands == 0) 1973 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV; 1974 else if (NumOperands == 1) { 1975 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 1976 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV; 1977 } else { 1978 for (unsigned i = 0, e = NumOperands; i != e; ++i) 1979 PushValueAndType(I.getOperand(i), InstID, Vals, VE); 1980 } 1981 } 1982 break; 1983 case Instruction::Br: 1984 { 1985 Code = bitc::FUNC_CODE_INST_BR; 1986 const BranchInst &II = cast<BranchInst>(I); 1987 Vals.push_back(VE.getValueID(II.getSuccessor(0))); 1988 if (II.isConditional()) { 1989 Vals.push_back(VE.getValueID(II.getSuccessor(1))); 1990 pushValue(II.getCondition(), InstID, Vals, VE); 1991 } 1992 } 1993 break; 1994 case Instruction::Switch: 1995 { 1996 Code = bitc::FUNC_CODE_INST_SWITCH; 1997 const SwitchInst &SI = cast<SwitchInst>(I); 1998 Vals.push_back(VE.getTypeID(SI.getCondition()->getType())); 1999 pushValue(SI.getCondition(), InstID, Vals, VE); 2000 Vals.push_back(VE.getValueID(SI.getDefaultDest())); 2001 for (SwitchInst::ConstCaseIt Case : SI.cases()) { 2002 Vals.push_back(VE.getValueID(Case.getCaseValue())); 2003 Vals.push_back(VE.getValueID(Case.getCaseSuccessor())); 2004 } 2005 } 2006 break; 2007 case Instruction::IndirectBr: 2008 Code = bitc::FUNC_CODE_INST_INDIRECTBR; 2009 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 2010 // Encode the address operand as relative, but not the basic blocks. 2011 pushValue(I.getOperand(0), InstID, Vals, VE); 2012 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) 2013 Vals.push_back(VE.getValueID(I.getOperand(i))); 2014 break; 2015 2016 case Instruction::Invoke: { 2017 const InvokeInst *II = cast<InvokeInst>(&I); 2018 const Value *Callee = II->getCalledValue(); 2019 FunctionType *FTy = II->getFunctionType(); 2020 2021 if (II->hasOperandBundles()) 2022 WriteOperandBundles(Stream, II, InstID, VE); 2023 2024 Code = bitc::FUNC_CODE_INST_INVOKE; 2025 2026 Vals.push_back(VE.getAttributeID(II->getAttributes())); 2027 Vals.push_back(II->getCallingConv() | 1 << 13); 2028 Vals.push_back(VE.getValueID(II->getNormalDest())); 2029 Vals.push_back(VE.getValueID(II->getUnwindDest())); 2030 Vals.push_back(VE.getTypeID(FTy)); 2031 PushValueAndType(Callee, InstID, Vals, VE); 2032 2033 // Emit value #'s for the fixed parameters. 2034 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2035 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param. 2036 2037 // Emit type/value pairs for varargs params. 2038 if (FTy->isVarArg()) { 2039 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3; 2040 i != e; ++i) 2041 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg 2042 } 2043 break; 2044 } 2045 case Instruction::Resume: 2046 Code = bitc::FUNC_CODE_INST_RESUME; 2047 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 2048 break; 2049 case Instruction::CleanupRet: { 2050 Code = bitc::FUNC_CODE_INST_CLEANUPRET; 2051 const auto &CRI = cast<CleanupReturnInst>(I); 2052 pushValue(CRI.getCleanupPad(), InstID, Vals, VE); 2053 if (CRI.hasUnwindDest()) 2054 Vals.push_back(VE.getValueID(CRI.getUnwindDest())); 2055 break; 2056 } 2057 case Instruction::CatchRet: { 2058 Code = bitc::FUNC_CODE_INST_CATCHRET; 2059 const auto &CRI = cast<CatchReturnInst>(I); 2060 pushValue(CRI.getCatchPad(), InstID, Vals, VE); 2061 Vals.push_back(VE.getValueID(CRI.getSuccessor())); 2062 break; 2063 } 2064 case Instruction::CleanupPad: 2065 case Instruction::CatchPad: { 2066 const auto &FuncletPad = cast<FuncletPadInst>(I); 2067 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD 2068 : bitc::FUNC_CODE_INST_CLEANUPPAD; 2069 pushValue(FuncletPad.getParentPad(), InstID, Vals, VE); 2070 2071 unsigned NumArgOperands = FuncletPad.getNumArgOperands(); 2072 Vals.push_back(NumArgOperands); 2073 for (unsigned Op = 0; Op != NumArgOperands; ++Op) 2074 PushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals, VE); 2075 break; 2076 } 2077 case Instruction::CatchSwitch: { 2078 Code = bitc::FUNC_CODE_INST_CATCHSWITCH; 2079 const auto &CatchSwitch = cast<CatchSwitchInst>(I); 2080 2081 pushValue(CatchSwitch.getParentPad(), InstID, Vals, VE); 2082 2083 unsigned NumHandlers = CatchSwitch.getNumHandlers(); 2084 Vals.push_back(NumHandlers); 2085 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers()) 2086 Vals.push_back(VE.getValueID(CatchPadBB)); 2087 2088 if (CatchSwitch.hasUnwindDest()) 2089 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest())); 2090 break; 2091 } 2092 case Instruction::Unreachable: 2093 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 2094 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV; 2095 break; 2096 2097 case Instruction::PHI: { 2098 const PHINode &PN = cast<PHINode>(I); 2099 Code = bitc::FUNC_CODE_INST_PHI; 2100 // With the newer instruction encoding, forward references could give 2101 // negative valued IDs. This is most common for PHIs, so we use 2102 // signed VBRs. 2103 SmallVector<uint64_t, 128> Vals64; 2104 Vals64.push_back(VE.getTypeID(PN.getType())); 2105 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 2106 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE); 2107 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i))); 2108 } 2109 // Emit a Vals64 vector and exit. 2110 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 2111 Vals64.clear(); 2112 return; 2113 } 2114 2115 case Instruction::LandingPad: { 2116 const LandingPadInst &LP = cast<LandingPadInst>(I); 2117 Code = bitc::FUNC_CODE_INST_LANDINGPAD; 2118 Vals.push_back(VE.getTypeID(LP.getType())); 2119 Vals.push_back(LP.isCleanup()); 2120 Vals.push_back(LP.getNumClauses()); 2121 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) { 2122 if (LP.isCatch(I)) 2123 Vals.push_back(LandingPadInst::Catch); 2124 else 2125 Vals.push_back(LandingPadInst::Filter); 2126 PushValueAndType(LP.getClause(I), InstID, Vals, VE); 2127 } 2128 break; 2129 } 2130 2131 case Instruction::Alloca: { 2132 Code = bitc::FUNC_CODE_INST_ALLOCA; 2133 const AllocaInst &AI = cast<AllocaInst>(I); 2134 Vals.push_back(VE.getTypeID(AI.getAllocatedType())); 2135 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 2136 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 2137 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1; 2138 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 && 2139 "not enough bits for maximum alignment"); 2140 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64"); 2141 AlignRecord |= AI.isUsedWithInAlloca() << 5; 2142 AlignRecord |= 1 << 6; 2143 // Reserve bit 7 for SwiftError flag. 2144 // AlignRecord |= AI.isSwiftError() << 7; 2145 Vals.push_back(AlignRecord); 2146 break; 2147 } 2148 2149 case Instruction::Load: 2150 if (cast<LoadInst>(I).isAtomic()) { 2151 Code = bitc::FUNC_CODE_INST_LOADATOMIC; 2152 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 2153 } else { 2154 Code = bitc::FUNC_CODE_INST_LOAD; 2155 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr 2156 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV; 2157 } 2158 Vals.push_back(VE.getTypeID(I.getType())); 2159 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1); 2160 Vals.push_back(cast<LoadInst>(I).isVolatile()); 2161 if (cast<LoadInst>(I).isAtomic()) { 2162 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering())); 2163 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope())); 2164 } 2165 break; 2166 case Instruction::Store: 2167 if (cast<StoreInst>(I).isAtomic()) 2168 Code = bitc::FUNC_CODE_INST_STOREATOMIC; 2169 else 2170 Code = bitc::FUNC_CODE_INST_STORE; 2171 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr 2172 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // valty + val 2173 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1); 2174 Vals.push_back(cast<StoreInst>(I).isVolatile()); 2175 if (cast<StoreInst>(I).isAtomic()) { 2176 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering())); 2177 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope())); 2178 } 2179 break; 2180 case Instruction::AtomicCmpXchg: 2181 Code = bitc::FUNC_CODE_INST_CMPXCHG; 2182 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr 2183 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // cmp. 2184 pushValue(I.getOperand(2), InstID, Vals, VE); // newval. 2185 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile()); 2186 Vals.push_back(GetEncodedOrdering( 2187 cast<AtomicCmpXchgInst>(I).getSuccessOrdering())); 2188 Vals.push_back(GetEncodedSynchScope( 2189 cast<AtomicCmpXchgInst>(I).getSynchScope())); 2190 Vals.push_back(GetEncodedOrdering( 2191 cast<AtomicCmpXchgInst>(I).getFailureOrdering())); 2192 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak()); 2193 break; 2194 case Instruction::AtomicRMW: 2195 Code = bitc::FUNC_CODE_INST_ATOMICRMW; 2196 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr 2197 pushValue(I.getOperand(1), InstID, Vals, VE); // val. 2198 Vals.push_back(GetEncodedRMWOperation( 2199 cast<AtomicRMWInst>(I).getOperation())); 2200 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile()); 2201 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering())); 2202 Vals.push_back(GetEncodedSynchScope( 2203 cast<AtomicRMWInst>(I).getSynchScope())); 2204 break; 2205 case Instruction::Fence: 2206 Code = bitc::FUNC_CODE_INST_FENCE; 2207 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering())); 2208 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope())); 2209 break; 2210 case Instruction::Call: { 2211 const CallInst &CI = cast<CallInst>(I); 2212 FunctionType *FTy = CI.getFunctionType(); 2213 2214 if (CI.hasOperandBundles()) 2215 WriteOperandBundles(Stream, &CI, InstID, VE); 2216 2217 Code = bitc::FUNC_CODE_INST_CALL; 2218 2219 Vals.push_back(VE.getAttributeID(CI.getAttributes())); 2220 2221 unsigned Flags = GetOptimizationFlags(&I); 2222 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV | 2223 unsigned(CI.isTailCall()) << bitc::CALL_TAIL | 2224 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL | 2225 1 << bitc::CALL_EXPLICIT_TYPE | 2226 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL | 2227 unsigned(Flags != 0) << bitc::CALL_FMF); 2228 if (Flags != 0) 2229 Vals.push_back(Flags); 2230 2231 Vals.push_back(VE.getTypeID(FTy)); 2232 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee 2233 2234 // Emit value #'s for the fixed parameters. 2235 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 2236 // Check for labels (can happen with asm labels). 2237 if (FTy->getParamType(i)->isLabelTy()) 2238 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); 2239 else 2240 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param. 2241 } 2242 2243 // Emit type/value pairs for varargs params. 2244 if (FTy->isVarArg()) { 2245 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands(); 2246 i != e; ++i) 2247 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs 2248 } 2249 break; 2250 } 2251 case Instruction::VAArg: 2252 Code = bitc::FUNC_CODE_INST_VAARG; 2253 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty 2254 pushValue(I.getOperand(0), InstID, Vals, VE); // valist. 2255 Vals.push_back(VE.getTypeID(I.getType())); // restype. 2256 break; 2257 } 2258 2259 Stream.EmitRecord(Code, Vals, AbbrevToUse); 2260 Vals.clear(); 2261 } 2262 2263 /// Emit names for globals/functions etc. The VSTOffsetPlaceholder, 2264 /// BitcodeStartBit and ModuleSummaryIndex are only passed for the module-level 2265 /// VST, where we are including a function bitcode index and need to 2266 /// backpatch the VST forward declaration record. 2267 static void WriteValueSymbolTable( 2268 const ValueSymbolTable &VST, const ValueEnumerator &VE, 2269 BitstreamWriter &Stream, uint64_t VSTOffsetPlaceholder = 0, 2270 uint64_t BitcodeStartBit = 0, 2271 DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>> 2272 *FunctionIndex = nullptr) { 2273 if (VST.empty()) { 2274 // WriteValueSymbolTableForwardDecl should have returned early as 2275 // well. Ensure this handling remains in sync by asserting that 2276 // the placeholder offset is not set. 2277 assert(VSTOffsetPlaceholder == 0); 2278 return; 2279 } 2280 2281 if (VSTOffsetPlaceholder > 0) { 2282 // Get the offset of the VST we are writing, and backpatch it into 2283 // the VST forward declaration record. 2284 uint64_t VSTOffset = Stream.GetCurrentBitNo(); 2285 // The BitcodeStartBit was the stream offset of the actual bitcode 2286 // (e.g. excluding any initial darwin header). 2287 VSTOffset -= BitcodeStartBit; 2288 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned"); 2289 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32); 2290 } 2291 2292 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 2293 2294 // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY 2295 // records, which are not used in the per-function VSTs. 2296 unsigned FnEntry8BitAbbrev; 2297 unsigned FnEntry7BitAbbrev; 2298 unsigned FnEntry6BitAbbrev; 2299 if (VSTOffsetPlaceholder > 0) { 2300 // 8-bit fixed-width VST_CODE_FNENTRY function strings. 2301 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2302 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY)); 2303 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 2304 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset 2305 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2306 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2307 FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv); 2308 2309 // 7-bit fixed width VST_CODE_FNENTRY function strings. 2310 Abbv = new BitCodeAbbrev(); 2311 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY)); 2312 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 2313 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset 2314 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2315 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 2316 FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv); 2317 2318 // 6-bit char6 VST_CODE_FNENTRY function strings. 2319 Abbv = new BitCodeAbbrev(); 2320 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY)); 2321 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 2322 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset 2323 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2324 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2325 FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv); 2326 } 2327 2328 // FIXME: Set up the abbrev, we know how many values there are! 2329 // FIXME: We know if the type names can use 7-bit ascii. 2330 SmallVector<unsigned, 64> NameVals; 2331 2332 for (const ValueName &Name : VST) { 2333 // Figure out the encoding to use for the name. 2334 StringEncoding Bits = 2335 getStringEncoding(Name.getKeyData(), Name.getKeyLength()); 2336 2337 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 2338 NameVals.push_back(VE.getValueID(Name.getValue())); 2339 2340 Function *F = dyn_cast<Function>(Name.getValue()); 2341 if (!F) { 2342 // If value is an alias, need to get the aliased base object to 2343 // see if it is a function. 2344 auto *GA = dyn_cast<GlobalAlias>(Name.getValue()); 2345 if (GA && GA->getBaseObject()) 2346 F = dyn_cast<Function>(GA->getBaseObject()); 2347 } 2348 2349 // VST_CODE_ENTRY: [valueid, namechar x N] 2350 // VST_CODE_FNENTRY: [valueid, funcoffset, namechar x N] 2351 // VST_CODE_BBENTRY: [bbid, namechar x N] 2352 unsigned Code; 2353 if (isa<BasicBlock>(Name.getValue())) { 2354 Code = bitc::VST_CODE_BBENTRY; 2355 if (Bits == SE_Char6) 2356 AbbrevToUse = VST_BBENTRY_6_ABBREV; 2357 } else if (F && !F->isDeclaration()) { 2358 // Must be the module-level VST, where we pass in the Index and 2359 // have a VSTOffsetPlaceholder. The function-level VST should not 2360 // contain any Function symbols. 2361 assert(FunctionIndex); 2362 assert(VSTOffsetPlaceholder > 0); 2363 2364 // Save the word offset of the function (from the start of the 2365 // actual bitcode written to the stream). 2366 uint64_t BitcodeIndex = 2367 (*FunctionIndex)[F]->bitcodeIndex() - BitcodeStartBit; 2368 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned"); 2369 NameVals.push_back(BitcodeIndex / 32); 2370 2371 Code = bitc::VST_CODE_FNENTRY; 2372 AbbrevToUse = FnEntry8BitAbbrev; 2373 if (Bits == SE_Char6) 2374 AbbrevToUse = FnEntry6BitAbbrev; 2375 else if (Bits == SE_Fixed7) 2376 AbbrevToUse = FnEntry7BitAbbrev; 2377 } else { 2378 Code = bitc::VST_CODE_ENTRY; 2379 if (Bits == SE_Char6) 2380 AbbrevToUse = VST_ENTRY_6_ABBREV; 2381 else if (Bits == SE_Fixed7) 2382 AbbrevToUse = VST_ENTRY_7_ABBREV; 2383 } 2384 2385 for (const auto P : Name.getKey()) 2386 NameVals.push_back((unsigned char)P); 2387 2388 // Emit the finished record. 2389 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 2390 NameVals.clear(); 2391 } 2392 Stream.ExitBlock(); 2393 } 2394 2395 /// Emit function names and summary offsets for the combined index 2396 /// used by ThinLTO. 2397 static void 2398 WriteCombinedValueSymbolTable(const ModuleSummaryIndex &Index, 2399 BitstreamWriter &Stream, 2400 std::map<uint64_t, unsigned> &GUIDToValueIdMap, 2401 uint64_t VSTOffsetPlaceholder) { 2402 assert(VSTOffsetPlaceholder > 0 && "Expected non-zero VSTOffsetPlaceholder"); 2403 // Get the offset of the VST we are writing, and backpatch it into 2404 // the VST forward declaration record. 2405 uint64_t VSTOffset = Stream.GetCurrentBitNo(); 2406 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned"); 2407 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32); 2408 2409 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 2410 2411 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2412 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_GVDEFENTRY)); 2413 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 2414 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // sumoffset 2415 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // guid 2416 unsigned DefEntryAbbrev = Stream.EmitAbbrev(Abbv); 2417 2418 Abbv = new BitCodeAbbrev(); 2419 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY)); 2420 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 2421 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid 2422 unsigned EntryAbbrev = Stream.EmitAbbrev(Abbv); 2423 2424 SmallVector<uint64_t, 64> NameVals; 2425 2426 for (const auto &FII : Index) { 2427 uint64_t FuncGUID = FII.first; 2428 const auto &VMI = GUIDToValueIdMap.find(FuncGUID); 2429 assert(VMI != GUIDToValueIdMap.end()); 2430 2431 for (const auto &FI : FII.second) { 2432 // VST_CODE_COMBINED_GVDEFENTRY: [valueid, sumoffset, guid] 2433 NameVals.push_back(VMI->second); 2434 NameVals.push_back(FI->bitcodeIndex()); 2435 NameVals.push_back(FuncGUID); 2436 2437 // Emit the finished record. 2438 Stream.EmitRecord(bitc::VST_CODE_COMBINED_GVDEFENTRY, NameVals, 2439 DefEntryAbbrev); 2440 NameVals.clear(); 2441 } 2442 GUIDToValueIdMap.erase(VMI); 2443 } 2444 for (const auto &GVI : GUIDToValueIdMap) { 2445 // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 2446 NameVals.push_back(GVI.second); 2447 NameVals.push_back(GVI.first); 2448 2449 // Emit the finished record. 2450 Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals, EntryAbbrev); 2451 NameVals.clear(); 2452 } 2453 Stream.ExitBlock(); 2454 } 2455 2456 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order, 2457 BitstreamWriter &Stream) { 2458 assert(Order.Shuffle.size() >= 2 && "Shuffle too small"); 2459 unsigned Code; 2460 if (isa<BasicBlock>(Order.V)) 2461 Code = bitc::USELIST_CODE_BB; 2462 else 2463 Code = bitc::USELIST_CODE_DEFAULT; 2464 2465 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end()); 2466 Record.push_back(VE.getValueID(Order.V)); 2467 Stream.EmitRecord(Code, Record); 2468 } 2469 2470 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE, 2471 BitstreamWriter &Stream) { 2472 assert(VE.shouldPreserveUseListOrder() && 2473 "Expected to be preserving use-list order"); 2474 2475 auto hasMore = [&]() { 2476 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F; 2477 }; 2478 if (!hasMore()) 2479 // Nothing to do. 2480 return; 2481 2482 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3); 2483 while (hasMore()) { 2484 WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream); 2485 VE.UseListOrders.pop_back(); 2486 } 2487 Stream.ExitBlock(); 2488 } 2489 2490 // Walk through the operands of a given User via worklist iteration and populate 2491 // the set of GlobalValue references encountered. Invoked either on an 2492 // Instruction or a GlobalVariable (which walks its initializer). 2493 static void findRefEdges(const User *CurUser, const ValueEnumerator &VE, 2494 DenseSet<unsigned> &RefEdges, 2495 SmallPtrSet<const User *, 8> &Visited) { 2496 SmallVector<const User *, 32> Worklist; 2497 Worklist.push_back(CurUser); 2498 2499 while (!Worklist.empty()) { 2500 const User *U = Worklist.pop_back_val(); 2501 2502 if (!Visited.insert(U).second) 2503 continue; 2504 2505 ImmutableCallSite CS(U); 2506 2507 for (const auto &OI : U->operands()) { 2508 const User *Operand = dyn_cast<User>(OI); 2509 if (!Operand) 2510 continue; 2511 if (isa<BlockAddress>(Operand)) 2512 continue; 2513 if (isa<GlobalValue>(Operand)) { 2514 // We have a reference to a global value. This should be added to 2515 // the reference set unless it is a callee. Callees are handled 2516 // specially by WriteFunction and are added to a separate list. 2517 if (!(CS && CS.isCallee(&OI))) 2518 RefEdges.insert(VE.getValueID(Operand)); 2519 continue; 2520 } 2521 Worklist.push_back(Operand); 2522 } 2523 } 2524 } 2525 2526 /// Emit a function body to the module stream. 2527 static void WriteFunction( 2528 const Function &F, const Module *M, ValueEnumerator &VE, 2529 BitstreamWriter &Stream, 2530 DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>> &FunctionIndex, 2531 bool EmitSummaryIndex) { 2532 // Save the bitcode index of the start of this function block for recording 2533 // in the VST. 2534 uint64_t BitcodeIndex = Stream.GetCurrentBitNo(); 2535 2536 bool HasProfileData = F.getEntryCount().hasValue(); 2537 std::unique_ptr<BlockFrequencyInfo> BFI; 2538 if (EmitSummaryIndex && HasProfileData) { 2539 Function &Func = const_cast<Function &>(F); 2540 LoopInfo LI{DominatorTree(Func)}; 2541 BranchProbabilityInfo BPI{Func, LI}; 2542 BFI = llvm::make_unique<BlockFrequencyInfo>(Func, BPI, LI); 2543 } 2544 2545 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 2546 VE.incorporateFunction(F); 2547 2548 SmallVector<unsigned, 64> Vals; 2549 2550 // Emit the number of basic blocks, so the reader can create them ahead of 2551 // time. 2552 Vals.push_back(VE.getBasicBlocks().size()); 2553 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 2554 Vals.clear(); 2555 2556 // If there are function-local constants, emit them now. 2557 unsigned CstStart, CstEnd; 2558 VE.getFunctionConstantRange(CstStart, CstEnd); 2559 WriteConstants(CstStart, CstEnd, VE, Stream, false); 2560 2561 // If there is function-local metadata, emit it now. 2562 writeFunctionMetadata(F, VE, Stream); 2563 2564 // Keep a running idea of what the instruction ID is. 2565 unsigned InstID = CstEnd; 2566 2567 bool NeedsMetadataAttachment = F.hasMetadata(); 2568 2569 DILocation *LastDL = nullptr; 2570 unsigned NumInsts = 0; 2571 // Map from callee ValueId to profile count. Used to accumulate profile 2572 // counts for all static calls to a given callee. 2573 DenseMap<unsigned, CalleeInfo> CallGraphEdges; 2574 DenseSet<unsigned> RefEdges; 2575 2576 SmallPtrSet<const User *, 8> Visited; 2577 // Finally, emit all the instructions, in order. 2578 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 2579 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 2580 I != E; ++I) { 2581 WriteInstruction(*I, InstID, VE, Stream, Vals); 2582 2583 if (!isa<DbgInfoIntrinsic>(I)) 2584 ++NumInsts; 2585 2586 if (!I->getType()->isVoidTy()) 2587 ++InstID; 2588 2589 if (EmitSummaryIndex) { 2590 if (auto CS = ImmutableCallSite(&*I)) { 2591 auto *CalledFunction = CS.getCalledFunction(); 2592 if (CalledFunction && CalledFunction->hasName() && 2593 !CalledFunction->isIntrinsic()) { 2594 auto ScaledCount = BFI ? BFI->getBlockProfileCount(&*BB) : None; 2595 unsigned CalleeId = VE.getValueID( 2596 M->getValueSymbolTable().lookup(CalledFunction->getName())); 2597 CallGraphEdges[CalleeId] += 2598 (ScaledCount ? ScaledCount.getValue() : 0); 2599 } 2600 } 2601 findRefEdges(&*I, VE, RefEdges, Visited); 2602 } 2603 2604 // If the instruction has metadata, write a metadata attachment later. 2605 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc(); 2606 2607 // If the instruction has a debug location, emit it. 2608 DILocation *DL = I->getDebugLoc(); 2609 if (!DL) 2610 continue; 2611 2612 if (DL == LastDL) { 2613 // Just repeat the same debug loc as last time. 2614 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals); 2615 continue; 2616 } 2617 2618 Vals.push_back(DL->getLine()); 2619 Vals.push_back(DL->getColumn()); 2620 Vals.push_back(VE.getMetadataOrNullID(DL->getScope())); 2621 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt())); 2622 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals); 2623 Vals.clear(); 2624 2625 LastDL = DL; 2626 } 2627 2628 std::unique_ptr<FunctionSummary> FuncSummary; 2629 if (EmitSummaryIndex) { 2630 FuncSummary = llvm::make_unique<FunctionSummary>(F.getLinkage(), NumInsts); 2631 FuncSummary->addCallGraphEdges(CallGraphEdges); 2632 FuncSummary->addRefEdges(RefEdges); 2633 } 2634 FunctionIndex[&F] = 2635 llvm::make_unique<GlobalValueInfo>(BitcodeIndex, std::move(FuncSummary)); 2636 2637 // Emit names for all the instructions etc. 2638 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream); 2639 2640 if (NeedsMetadataAttachment) 2641 WriteMetadataAttachment(F, VE, Stream); 2642 if (VE.shouldPreserveUseListOrder()) 2643 WriteUseListBlock(&F, VE, Stream); 2644 VE.purgeFunction(); 2645 Stream.ExitBlock(); 2646 } 2647 2648 // Emit blockinfo, which defines the standard abbreviations etc. 2649 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) { 2650 // We only want to emit block info records for blocks that have multiple 2651 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. 2652 // Other blocks can define their abbrevs inline. 2653 Stream.EnterBlockInfoBlock(2); 2654 2655 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings. 2656 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2657 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 2658 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2659 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2660 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2661 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2662 Abbv) != VST_ENTRY_8_ABBREV) 2663 llvm_unreachable("Unexpected abbrev ordering!"); 2664 } 2665 2666 { // 7-bit fixed width VST_CODE_ENTRY strings. 2667 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2668 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 2669 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2670 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2671 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 2672 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2673 Abbv) != VST_ENTRY_7_ABBREV) 2674 llvm_unreachable("Unexpected abbrev ordering!"); 2675 } 2676 { // 6-bit char6 VST_CODE_ENTRY strings. 2677 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2678 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 2679 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2680 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2681 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2682 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2683 Abbv) != VST_ENTRY_6_ABBREV) 2684 llvm_unreachable("Unexpected abbrev ordering!"); 2685 } 2686 { // 6-bit char6 VST_CODE_BBENTRY strings. 2687 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2688 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY)); 2689 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2690 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2691 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2692 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2693 Abbv) != VST_BBENTRY_6_ABBREV) 2694 llvm_unreachable("Unexpected abbrev ordering!"); 2695 } 2696 2697 2698 2699 { // SETTYPE abbrev for CONSTANTS_BLOCK. 2700 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2701 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); 2702 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2703 VE.computeBitsRequiredForTypeIndicies())); 2704 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 2705 Abbv) != CONSTANTS_SETTYPE_ABBREV) 2706 llvm_unreachable("Unexpected abbrev ordering!"); 2707 } 2708 2709 { // INTEGER abbrev for CONSTANTS_BLOCK. 2710 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2711 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); 2712 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2713 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 2714 Abbv) != CONSTANTS_INTEGER_ABBREV) 2715 llvm_unreachable("Unexpected abbrev ordering!"); 2716 } 2717 2718 { // CE_CAST abbrev for CONSTANTS_BLOCK. 2719 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2720 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); 2721 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc 2722 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid 2723 VE.computeBitsRequiredForTypeIndicies())); 2724 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 2725 2726 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 2727 Abbv) != CONSTANTS_CE_CAST_Abbrev) 2728 llvm_unreachable("Unexpected abbrev ordering!"); 2729 } 2730 { // NULL abbrev for CONSTANTS_BLOCK. 2731 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2732 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL)); 2733 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 2734 Abbv) != CONSTANTS_NULL_Abbrev) 2735 llvm_unreachable("Unexpected abbrev ordering!"); 2736 } 2737 2738 // FIXME: This should only use space for first class types! 2739 2740 { // INST_LOAD abbrev for FUNCTION_BLOCK. 2741 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2742 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); 2743 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr 2744 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 2745 VE.computeBitsRequiredForTypeIndicies())); 2746 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align 2747 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile 2748 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 2749 Abbv) != FUNCTION_INST_LOAD_ABBREV) 2750 llvm_unreachable("Unexpected abbrev ordering!"); 2751 } 2752 { // INST_BINOP abbrev for FUNCTION_BLOCK. 2753 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2754 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 2755 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 2756 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 2757 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 2758 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 2759 Abbv) != FUNCTION_INST_BINOP_ABBREV) 2760 llvm_unreachable("Unexpected abbrev ordering!"); 2761 } 2762 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK. 2763 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2764 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 2765 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 2766 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 2767 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 2768 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags 2769 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 2770 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV) 2771 llvm_unreachable("Unexpected abbrev ordering!"); 2772 } 2773 { // INST_CAST abbrev for FUNCTION_BLOCK. 2774 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2775 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 2776 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 2777 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 2778 VE.computeBitsRequiredForTypeIndicies())); 2779 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 2780 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 2781 Abbv) != FUNCTION_INST_CAST_ABBREV) 2782 llvm_unreachable("Unexpected abbrev ordering!"); 2783 } 2784 2785 { // INST_RET abbrev for FUNCTION_BLOCK. 2786 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2787 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 2788 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 2789 Abbv) != FUNCTION_INST_RET_VOID_ABBREV) 2790 llvm_unreachable("Unexpected abbrev ordering!"); 2791 } 2792 { // INST_RET abbrev for FUNCTION_BLOCK. 2793 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2794 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 2795 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID 2796 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 2797 Abbv) != FUNCTION_INST_RET_VAL_ABBREV) 2798 llvm_unreachable("Unexpected abbrev ordering!"); 2799 } 2800 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK. 2801 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2802 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE)); 2803 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 2804 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV) 2805 llvm_unreachable("Unexpected abbrev ordering!"); 2806 } 2807 { 2808 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2809 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP)); 2810 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 2811 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 2812 Log2_32_Ceil(VE.getTypes().size() + 1))); 2813 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2814 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 2815 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 2816 FUNCTION_INST_GEP_ABBREV) 2817 llvm_unreachable("Unexpected abbrev ordering!"); 2818 } 2819 2820 Stream.ExitBlock(); 2821 } 2822 2823 /// Write the module path strings, currently only used when generating 2824 /// a combined index file. 2825 static void WriteModStrings(const ModuleSummaryIndex &I, 2826 BitstreamWriter &Stream) { 2827 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3); 2828 2829 // TODO: See which abbrev sizes we actually need to emit 2830 2831 // 8-bit fixed-width MST_ENTRY strings. 2832 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2833 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 2834 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2835 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2836 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2837 unsigned Abbrev8Bit = Stream.EmitAbbrev(Abbv); 2838 2839 // 7-bit fixed width MST_ENTRY strings. 2840 Abbv = new BitCodeAbbrev(); 2841 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 2842 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2843 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2844 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 2845 unsigned Abbrev7Bit = Stream.EmitAbbrev(Abbv); 2846 2847 // 6-bit char6 MST_ENTRY strings. 2848 Abbv = new BitCodeAbbrev(); 2849 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 2850 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2851 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2852 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2853 unsigned Abbrev6Bit = Stream.EmitAbbrev(Abbv); 2854 2855 SmallVector<unsigned, 64> NameVals; 2856 for (const StringMapEntry<uint64_t> &MPSE : I.modulePaths()) { 2857 StringEncoding Bits = 2858 getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size()); 2859 unsigned AbbrevToUse = Abbrev8Bit; 2860 if (Bits == SE_Char6) 2861 AbbrevToUse = Abbrev6Bit; 2862 else if (Bits == SE_Fixed7) 2863 AbbrevToUse = Abbrev7Bit; 2864 2865 NameVals.push_back(MPSE.getValue()); 2866 2867 for (const auto P : MPSE.getKey()) 2868 NameVals.push_back((unsigned char)P); 2869 2870 // Emit the finished record. 2871 Stream.EmitRecord(bitc::MST_CODE_ENTRY, NameVals, AbbrevToUse); 2872 NameVals.clear(); 2873 } 2874 Stream.ExitBlock(); 2875 } 2876 2877 // Helper to emit a single function summary record. 2878 static void WritePerModuleFunctionSummaryRecord( 2879 SmallVector<uint64_t, 64> &NameVals, FunctionSummary *FS, unsigned ValueID, 2880 unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev, 2881 BitstreamWriter &Stream, const Function &F) { 2882 assert(FS); 2883 NameVals.push_back(ValueID); 2884 NameVals.push_back(getEncodedLinkage(FS->linkage())); 2885 NameVals.push_back(FS->instCount()); 2886 NameVals.push_back(FS->refs().size()); 2887 2888 for (auto &RI : FS->refs()) 2889 NameVals.push_back(RI); 2890 2891 bool HasProfileData = F.getEntryCount().hasValue(); 2892 for (auto &ECI : FS->calls()) { 2893 NameVals.push_back(ECI.first); 2894 assert(ECI.second.CallsiteCount > 0 && "Expected at least one callsite"); 2895 NameVals.push_back(ECI.second.CallsiteCount); 2896 if (HasProfileData) 2897 NameVals.push_back(ECI.second.ProfileCount); 2898 } 2899 2900 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev); 2901 unsigned Code = 2902 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE); 2903 2904 // Emit the finished record. 2905 Stream.EmitRecord(Code, NameVals, FSAbbrev); 2906 NameVals.clear(); 2907 } 2908 2909 // Collect the global value references in the given variable's initializer, 2910 // and emit them in a summary record. 2911 static void WriteModuleLevelReferences(const GlobalVariable &V, 2912 const ValueEnumerator &VE, 2913 SmallVector<uint64_t, 64> &NameVals, 2914 unsigned FSModRefsAbbrev, 2915 BitstreamWriter &Stream) { 2916 // Only interested in recording variable defs in the summary. 2917 if (V.isDeclaration()) 2918 return; 2919 DenseSet<unsigned> RefEdges; 2920 SmallPtrSet<const User *, 8> Visited; 2921 findRefEdges(&V, VE, RefEdges, Visited); 2922 NameVals.push_back(VE.getValueID(&V)); 2923 NameVals.push_back(getEncodedLinkage(V.getLinkage())); 2924 for (auto RefId : RefEdges) { 2925 NameVals.push_back(RefId); 2926 } 2927 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals, 2928 FSModRefsAbbrev); 2929 NameVals.clear(); 2930 } 2931 2932 /// Emit the per-module summary section alongside the rest of 2933 /// the module's bitcode. 2934 static void WritePerModuleGlobalValueSummary( 2935 DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>> &FunctionIndex, 2936 const Module *M, const ValueEnumerator &VE, BitstreamWriter &Stream) { 2937 if (M->empty()) 2938 return; 2939 2940 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3); 2941 2942 // Abbrev for FS_PERMODULE. 2943 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 2944 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE)); 2945 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 2946 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage 2947 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 2948 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 2949 // numrefs x valueid, n x (valueid, callsitecount) 2950 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2951 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2952 unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv); 2953 2954 // Abbrev for FS_PERMODULE_PROFILE. 2955 Abbv = new BitCodeAbbrev(); 2956 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE)); 2957 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 2958 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage 2959 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 2960 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 2961 // numrefs x valueid, n x (valueid, callsitecount, profilecount) 2962 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2963 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2964 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv); 2965 2966 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS. 2967 Abbv = new BitCodeAbbrev(); 2968 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS)); 2969 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 2970 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage 2971 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 2972 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2973 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv); 2974 2975 SmallVector<uint64_t, 64> NameVals; 2976 // Iterate over the list of functions instead of the FunctionIndex map to 2977 // ensure the ordering is stable. 2978 for (const Function &F : *M) { 2979 if (F.isDeclaration()) 2980 continue; 2981 // Skip anonymous functions. We will emit a function summary for 2982 // any aliases below. 2983 if (!F.hasName()) 2984 continue; 2985 2986 assert(FunctionIndex.count(&F) == 1); 2987 2988 WritePerModuleFunctionSummaryRecord( 2989 NameVals, cast<FunctionSummary>(FunctionIndex[&F]->summary()), 2990 VE.getValueID(M->getValueSymbolTable().lookup(F.getName())), 2991 FSCallsAbbrev, FSCallsProfileAbbrev, Stream, F); 2992 } 2993 2994 for (const GlobalAlias &A : M->aliases()) { 2995 if (!A.getBaseObject()) 2996 continue; 2997 const Function *F = dyn_cast<Function>(A.getBaseObject()); 2998 if (!F || F->isDeclaration()) 2999 continue; 3000 3001 assert(FunctionIndex.count(F) == 1); 3002 FunctionSummary *FS = 3003 cast<FunctionSummary>(FunctionIndex[F]->summary()); 3004 // Add the alias to the reference list of aliasee function. 3005 FS->addRefEdge( 3006 VE.getValueID(M->getValueSymbolTable().lookup(A.getName()))); 3007 WritePerModuleFunctionSummaryRecord( 3008 NameVals, FS, 3009 VE.getValueID(M->getValueSymbolTable().lookup(A.getName())), 3010 FSCallsAbbrev, FSCallsProfileAbbrev, Stream, *F); 3011 } 3012 3013 // Capture references from GlobalVariable initializers, which are outside 3014 // of a function scope. 3015 for (const GlobalVariable &G : M->globals()) 3016 WriteModuleLevelReferences(G, VE, NameVals, FSModRefsAbbrev, Stream); 3017 for (const GlobalAlias &A : M->aliases()) 3018 if (auto *GV = dyn_cast<GlobalVariable>(A.getBaseObject())) 3019 WriteModuleLevelReferences(*GV, VE, NameVals, FSModRefsAbbrev, Stream); 3020 3021 Stream.ExitBlock(); 3022 } 3023 3024 /// Emit the combined summary section into the combined index file. 3025 static void WriteCombinedGlobalValueSummary( 3026 const ModuleSummaryIndex &I, BitstreamWriter &Stream, 3027 std::map<uint64_t, unsigned> &GUIDToValueIdMap, unsigned GlobalValueId) { 3028 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3); 3029 3030 // Abbrev for FS_COMBINED. 3031 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3032 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED)); 3033 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 3034 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage 3035 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 3036 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3037 // numrefs x valueid, n x (valueid, callsitecount) 3038 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3039 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3040 unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv); 3041 3042 // Abbrev for FS_COMBINED_PROFILE. 3043 Abbv = new BitCodeAbbrev(); 3044 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE)); 3045 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 3046 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage 3047 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 3048 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3049 // numrefs x valueid, n x (valueid, callsitecount, profilecount) 3050 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3051 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3052 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv); 3053 3054 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS. 3055 Abbv = new BitCodeAbbrev(); 3056 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS)); 3057 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 3058 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage 3059 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 3060 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3061 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv); 3062 3063 SmallVector<uint64_t, 64> NameVals; 3064 for (const auto &FII : I) { 3065 for (auto &FI : FII.second) { 3066 GlobalValueSummary *S = FI->summary(); 3067 assert(S); 3068 3069 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) { 3070 NameVals.push_back(I.getModuleId(VS->modulePath())); 3071 NameVals.push_back(getEncodedLinkage(VS->linkage())); 3072 for (auto &RI : VS->refs()) { 3073 const auto &VMI = GUIDToValueIdMap.find(RI); 3074 unsigned RefId; 3075 // If this GUID doesn't have an entry, assign one. 3076 if (VMI == GUIDToValueIdMap.end()) { 3077 GUIDToValueIdMap[RI] = ++GlobalValueId; 3078 RefId = GlobalValueId; 3079 } else { 3080 RefId = VMI->second; 3081 } 3082 NameVals.push_back(RefId); 3083 } 3084 3085 // Record the starting offset of this summary entry for use 3086 // in the VST entry. Add the current code size since the 3087 // reader will invoke readRecord after the abbrev id read. 3088 FI->setBitcodeIndex(Stream.GetCurrentBitNo() + 3089 Stream.GetAbbrevIDWidth()); 3090 3091 // Emit the finished record. 3092 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals, 3093 FSModRefsAbbrev); 3094 NameVals.clear(); 3095 continue; 3096 } 3097 3098 auto *FS = cast<FunctionSummary>(S); 3099 NameVals.push_back(I.getModuleId(FS->modulePath())); 3100 NameVals.push_back(getEncodedLinkage(FS->linkage())); 3101 NameVals.push_back(FS->instCount()); 3102 NameVals.push_back(FS->refs().size()); 3103 3104 for (auto &RI : FS->refs()) { 3105 const auto &VMI = GUIDToValueIdMap.find(RI); 3106 unsigned RefId; 3107 // If this GUID doesn't have an entry, assign one. 3108 if (VMI == GUIDToValueIdMap.end()) { 3109 GUIDToValueIdMap[RI] = ++GlobalValueId; 3110 RefId = GlobalValueId; 3111 } else { 3112 RefId = VMI->second; 3113 } 3114 NameVals.push_back(RefId); 3115 } 3116 3117 bool HasProfileData = false; 3118 for (auto &EI : FS->calls()) { 3119 HasProfileData |= EI.second.ProfileCount != 0; 3120 if (HasProfileData) 3121 break; 3122 } 3123 3124 for (auto &EI : FS->calls()) { 3125 const auto &VMI = GUIDToValueIdMap.find(EI.first); 3126 // If this GUID doesn't have an entry, it doesn't have a function 3127 // summary and we don't need to record any calls to it. 3128 if (VMI == GUIDToValueIdMap.end()) 3129 continue; 3130 NameVals.push_back(VMI->second); 3131 assert(EI.second.CallsiteCount > 0 && "Expected at least one callsite"); 3132 NameVals.push_back(EI.second.CallsiteCount); 3133 if (HasProfileData) 3134 NameVals.push_back(EI.second.ProfileCount); 3135 } 3136 3137 // Record the starting offset of this summary entry for use 3138 // in the VST entry. Add the current code size since the 3139 // reader will invoke readRecord after the abbrev id read. 3140 FI->setBitcodeIndex(Stream.GetCurrentBitNo() + Stream.GetAbbrevIDWidth()); 3141 3142 unsigned FSAbbrev = 3143 (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev); 3144 unsigned Code = 3145 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED); 3146 3147 // Emit the finished record. 3148 Stream.EmitRecord(Code, NameVals, FSAbbrev); 3149 NameVals.clear(); 3150 } 3151 } 3152 3153 Stream.ExitBlock(); 3154 } 3155 3156 // Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the 3157 // current llvm version, and a record for the epoch number. 3158 static void WriteIdentificationBlock(const Module *M, BitstreamWriter &Stream) { 3159 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5); 3160 3161 // Write the "user readable" string identifying the bitcode producer 3162 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 3163 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING)); 3164 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3165 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3166 auto StringAbbrev = Stream.EmitAbbrev(Abbv); 3167 WriteStringRecord(bitc::IDENTIFICATION_CODE_STRING, 3168 "LLVM" LLVM_VERSION_STRING, StringAbbrev, Stream); 3169 3170 // Write the epoch version 3171 Abbv = new BitCodeAbbrev(); 3172 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH)); 3173 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 3174 auto EpochAbbrev = Stream.EmitAbbrev(Abbv); 3175 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH}; 3176 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev); 3177 Stream.ExitBlock(); 3178 } 3179 3180 /// WriteModule - Emit the specified module to the bitstream. 3181 static void WriteModule(const Module *M, BitstreamWriter &Stream, 3182 bool ShouldPreserveUseListOrder, 3183 uint64_t BitcodeStartBit, bool EmitSummaryIndex) { 3184 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 3185 3186 SmallVector<unsigned, 1> Vals; 3187 unsigned CurVersion = 1; 3188 Vals.push_back(CurVersion); 3189 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals); 3190 3191 // Analyze the module, enumerating globals, functions, etc. 3192 ValueEnumerator VE(*M, ShouldPreserveUseListOrder); 3193 3194 // Emit blockinfo, which defines the standard abbreviations etc. 3195 WriteBlockInfo(VE, Stream); 3196 3197 // Emit information about attribute groups. 3198 WriteAttributeGroupTable(VE, Stream); 3199 3200 // Emit information about parameter attributes. 3201 WriteAttributeTable(VE, Stream); 3202 3203 // Emit information describing all of the types in the module. 3204 WriteTypeTable(VE, Stream); 3205 3206 writeComdats(VE, Stream); 3207 3208 // Emit top-level description of module, including target triple, inline asm, 3209 // descriptors for global variables, and function prototype info. 3210 uint64_t VSTOffsetPlaceholder = WriteModuleInfo(M, VE, Stream); 3211 3212 // Emit constants. 3213 WriteModuleConstants(VE, Stream); 3214 3215 // Emit metadata. 3216 writeModuleMetadata(*M, VE, Stream); 3217 3218 // Emit metadata. 3219 WriteModuleMetadataStore(M, Stream); 3220 3221 // Emit module-level use-lists. 3222 if (VE.shouldPreserveUseListOrder()) 3223 WriteUseListBlock(nullptr, VE, Stream); 3224 3225 WriteOperandBundleTags(M, Stream); 3226 3227 // Emit function bodies. 3228 DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>> FunctionIndex; 3229 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) 3230 if (!F->isDeclaration()) 3231 WriteFunction(*F, M, VE, Stream, FunctionIndex, EmitSummaryIndex); 3232 3233 // Need to write after the above call to WriteFunction which populates 3234 // the summary information in the index. 3235 if (EmitSummaryIndex) 3236 WritePerModuleGlobalValueSummary(FunctionIndex, M, VE, Stream); 3237 3238 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream, 3239 VSTOffsetPlaceholder, BitcodeStartBit, &FunctionIndex); 3240 3241 Stream.ExitBlock(); 3242 } 3243 3244 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a 3245 /// header and trailer to make it compatible with the system archiver. To do 3246 /// this we emit the following header, and then emit a trailer that pads the 3247 /// file out to be a multiple of 16 bytes. 3248 /// 3249 /// struct bc_header { 3250 /// uint32_t Magic; // 0x0B17C0DE 3251 /// uint32_t Version; // Version, currently always 0. 3252 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file. 3253 /// uint32_t BitcodeSize; // Size of traditional bitcode file. 3254 /// uint32_t CPUType; // CPU specifier. 3255 /// ... potentially more later ... 3256 /// }; 3257 3258 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer, 3259 uint32_t &Position) { 3260 support::endian::write32le(&Buffer[Position], Value); 3261 Position += 4; 3262 } 3263 3264 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer, 3265 const Triple &TT) { 3266 unsigned CPUType = ~0U; 3267 3268 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*, 3269 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic 3270 // number from /usr/include/mach/machine.h. It is ok to reproduce the 3271 // specific constants here because they are implicitly part of the Darwin ABI. 3272 enum { 3273 DARWIN_CPU_ARCH_ABI64 = 0x01000000, 3274 DARWIN_CPU_TYPE_X86 = 7, 3275 DARWIN_CPU_TYPE_ARM = 12, 3276 DARWIN_CPU_TYPE_POWERPC = 18 3277 }; 3278 3279 Triple::ArchType Arch = TT.getArch(); 3280 if (Arch == Triple::x86_64) 3281 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64; 3282 else if (Arch == Triple::x86) 3283 CPUType = DARWIN_CPU_TYPE_X86; 3284 else if (Arch == Triple::ppc) 3285 CPUType = DARWIN_CPU_TYPE_POWERPC; 3286 else if (Arch == Triple::ppc64) 3287 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64; 3288 else if (Arch == Triple::arm || Arch == Triple::thumb) 3289 CPUType = DARWIN_CPU_TYPE_ARM; 3290 3291 // Traditional Bitcode starts after header. 3292 assert(Buffer.size() >= BWH_HeaderSize && 3293 "Expected header size to be reserved"); 3294 unsigned BCOffset = BWH_HeaderSize; 3295 unsigned BCSize = Buffer.size() - BWH_HeaderSize; 3296 3297 // Write the magic and version. 3298 unsigned Position = 0; 3299 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position); 3300 WriteInt32ToBuffer(0 , Buffer, Position); // Version. 3301 WriteInt32ToBuffer(BCOffset , Buffer, Position); 3302 WriteInt32ToBuffer(BCSize , Buffer, Position); 3303 WriteInt32ToBuffer(CPUType , Buffer, Position); 3304 3305 // If the file is not a multiple of 16 bytes, insert dummy padding. 3306 while (Buffer.size() & 15) 3307 Buffer.push_back(0); 3308 } 3309 3310 /// Helper to write the header common to all bitcode files. 3311 static void WriteBitcodeHeader(BitstreamWriter &Stream) { 3312 // Emit the file header. 3313 Stream.Emit((unsigned)'B', 8); 3314 Stream.Emit((unsigned)'C', 8); 3315 Stream.Emit(0x0, 4); 3316 Stream.Emit(0xC, 4); 3317 Stream.Emit(0xE, 4); 3318 Stream.Emit(0xD, 4); 3319 } 3320 3321 /// WriteBitcodeToFile - Write the specified module to the specified output 3322 /// stream. 3323 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out, 3324 bool ShouldPreserveUseListOrder, 3325 bool EmitSummaryIndex) { 3326 SmallVector<char, 0> Buffer; 3327 Buffer.reserve(256*1024); 3328 3329 // If this is darwin or another generic macho target, reserve space for the 3330 // header. 3331 Triple TT(M->getTargetTriple()); 3332 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 3333 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0); 3334 3335 // Emit the module into the buffer. 3336 { 3337 BitstreamWriter Stream(Buffer); 3338 // Save the start bit of the actual bitcode, in case there is space 3339 // saved at the start for the darwin header above. The reader stream 3340 // will start at the bitcode, and we need the offset of the VST 3341 // to line up. 3342 uint64_t BitcodeStartBit = Stream.GetCurrentBitNo(); 3343 3344 // Emit the file header. 3345 WriteBitcodeHeader(Stream); 3346 3347 WriteIdentificationBlock(M, Stream); 3348 3349 // Emit the module. 3350 WriteModule(M, Stream, ShouldPreserveUseListOrder, BitcodeStartBit, 3351 EmitSummaryIndex); 3352 } 3353 3354 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 3355 EmitDarwinBCHeaderAndTrailer(Buffer, TT); 3356 3357 // Write the generated bitstream to "Out". 3358 Out.write((char*)&Buffer.front(), Buffer.size()); 3359 } 3360 3361 // Write the specified module summary index to the given raw output stream, 3362 // where it will be written in a new bitcode block. This is used when 3363 // writing the combined index file for ThinLTO. 3364 void llvm::WriteIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out) { 3365 SmallVector<char, 0> Buffer; 3366 Buffer.reserve(256 * 1024); 3367 3368 BitstreamWriter Stream(Buffer); 3369 3370 // Emit the bitcode header. 3371 WriteBitcodeHeader(Stream); 3372 3373 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 3374 3375 SmallVector<unsigned, 1> Vals; 3376 unsigned CurVersion = 1; 3377 Vals.push_back(CurVersion); 3378 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals); 3379 3380 // If we have a VST, write the VSTOFFSET record placeholder and record 3381 // its offset. 3382 uint64_t VSTOffsetPlaceholder = WriteValueSymbolTableForwardDecl(Stream); 3383 3384 // Write the module paths in the combined index. 3385 WriteModStrings(Index, Stream); 3386 3387 // Assign unique value ids to all functions in the index for use 3388 // in writing out the call graph edges. Save the mapping from GUID 3389 // to the new global value id to use when writing those edges, which 3390 // are currently saved in the index in terms of GUID. 3391 std::map<uint64_t, unsigned> GUIDToValueIdMap; 3392 unsigned GlobalValueId = 0; 3393 for (auto &II : Index) 3394 GUIDToValueIdMap[II.first] = ++GlobalValueId; 3395 3396 // Write the summary combined index records. 3397 WriteCombinedGlobalValueSummary(Index, Stream, GUIDToValueIdMap, 3398 GlobalValueId); 3399 3400 // Need a special VST writer for the combined index (we don't have a 3401 // real VST and real values when this is invoked). 3402 WriteCombinedValueSymbolTable(Index, Stream, GUIDToValueIdMap, 3403 VSTOffsetPlaceholder); 3404 3405 Stream.ExitBlock(); 3406 3407 Out.write((char *)&Buffer.front(), Buffer.size()); 3408 } 3409