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