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