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