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