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