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