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