1 //===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Bitcode writer implementation. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Bitcode/BitcodeWriter.h" 14 #include "ValueEnumerator.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallString.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/StringMap.h" 25 #include "llvm/ADT/StringRef.h" 26 #include "llvm/Bitcode/BitcodeCommon.h" 27 #include "llvm/Bitcode/BitcodeReader.h" 28 #include "llvm/Bitcode/LLVMBitCodes.h" 29 #include "llvm/Bitstream/BitCodes.h" 30 #include "llvm/Bitstream/BitstreamWriter.h" 31 #include "llvm/Config/llvm-config.h" 32 #include "llvm/IR/Attributes.h" 33 #include "llvm/IR/BasicBlock.h" 34 #include "llvm/IR/Comdat.h" 35 #include "llvm/IR/Constant.h" 36 #include "llvm/IR/Constants.h" 37 #include "llvm/IR/DebugInfoMetadata.h" 38 #include "llvm/IR/DebugLoc.h" 39 #include "llvm/IR/DerivedTypes.h" 40 #include "llvm/IR/Function.h" 41 #include "llvm/IR/GlobalAlias.h" 42 #include "llvm/IR/GlobalIFunc.h" 43 #include "llvm/IR/GlobalObject.h" 44 #include "llvm/IR/GlobalValue.h" 45 #include "llvm/IR/GlobalVariable.h" 46 #include "llvm/IR/InlineAsm.h" 47 #include "llvm/IR/InstrTypes.h" 48 #include "llvm/IR/Instruction.h" 49 #include "llvm/IR/Instructions.h" 50 #include "llvm/IR/LLVMContext.h" 51 #include "llvm/IR/Metadata.h" 52 #include "llvm/IR/Module.h" 53 #include "llvm/IR/ModuleSummaryIndex.h" 54 #include "llvm/IR/Operator.h" 55 #include "llvm/IR/Type.h" 56 #include "llvm/IR/UseListOrder.h" 57 #include "llvm/IR/Value.h" 58 #include "llvm/IR/ValueSymbolTable.h" 59 #include "llvm/MC/StringTableBuilder.h" 60 #include "llvm/MC/TargetRegistry.h" 61 #include "llvm/Object/IRSymtab.h" 62 #include "llvm/Support/AtomicOrdering.h" 63 #include "llvm/Support/Casting.h" 64 #include "llvm/Support/CommandLine.h" 65 #include "llvm/Support/Endian.h" 66 #include "llvm/Support/Error.h" 67 #include "llvm/Support/ErrorHandling.h" 68 #include "llvm/Support/MathExtras.h" 69 #include "llvm/Support/SHA1.h" 70 #include "llvm/Support/raw_ostream.h" 71 #include "llvm/TargetParser/Triple.h" 72 #include <algorithm> 73 #include <cassert> 74 #include <cstddef> 75 #include <cstdint> 76 #include <iterator> 77 #include <map> 78 #include <memory> 79 #include <optional> 80 #include <string> 81 #include <utility> 82 #include <vector> 83 84 using namespace llvm; 85 86 static cl::opt<unsigned> 87 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25), 88 cl::desc("Number of metadatas above which we emit an index " 89 "to enable lazy-loading")); 90 static cl::opt<uint32_t> FlushThreshold( 91 "bitcode-flush-threshold", cl::Hidden, cl::init(512), 92 cl::desc("The threshold (unit M) for flushing LLVM bitcode.")); 93 94 static cl::opt<bool> WriteRelBFToSummary( 95 "write-relbf-to-summary", cl::Hidden, cl::init(false), 96 cl::desc("Write relative block frequency to function summary ")); 97 98 namespace llvm { 99 extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold; 100 } 101 102 extern bool WriteNewDbgInfoFormatToBitcode; 103 extern llvm::cl::opt<bool> UseNewDbgInfoFormat; 104 105 namespace { 106 107 /// These are manifest constants used by the bitcode writer. They do not need to 108 /// be kept in sync with the reader, but need to be consistent within this file. 109 enum { 110 // VALUE_SYMTAB_BLOCK abbrev id's. 111 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 112 VST_ENTRY_7_ABBREV, 113 VST_ENTRY_6_ABBREV, 114 VST_BBENTRY_6_ABBREV, 115 116 // CONSTANTS_BLOCK abbrev id's. 117 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 118 CONSTANTS_INTEGER_ABBREV, 119 CONSTANTS_CE_CAST_Abbrev, 120 CONSTANTS_NULL_Abbrev, 121 122 // FUNCTION_BLOCK abbrev id's. 123 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 124 FUNCTION_INST_UNOP_ABBREV, 125 FUNCTION_INST_UNOP_FLAGS_ABBREV, 126 FUNCTION_INST_BINOP_ABBREV, 127 FUNCTION_INST_BINOP_FLAGS_ABBREV, 128 FUNCTION_INST_CAST_ABBREV, 129 FUNCTION_INST_CAST_FLAGS_ABBREV, 130 FUNCTION_INST_RET_VOID_ABBREV, 131 FUNCTION_INST_RET_VAL_ABBREV, 132 FUNCTION_INST_UNREACHABLE_ABBREV, 133 FUNCTION_INST_GEP_ABBREV, 134 FUNCTION_DEBUG_RECORD_VALUE_ABBREV, 135 }; 136 137 /// Abstract class to manage the bitcode writing, subclassed for each bitcode 138 /// file type. 139 class BitcodeWriterBase { 140 protected: 141 /// The stream created and owned by the client. 142 BitstreamWriter &Stream; 143 144 StringTableBuilder &StrtabBuilder; 145 146 public: 147 /// Constructs a BitcodeWriterBase object that writes to the provided 148 /// \p Stream. 149 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder) 150 : Stream(Stream), StrtabBuilder(StrtabBuilder) {} 151 152 protected: 153 void writeModuleVersion(); 154 }; 155 156 void BitcodeWriterBase::writeModuleVersion() { 157 // VERSION: [version#] 158 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2}); 159 } 160 161 /// Base class to manage the module bitcode writing, currently subclassed for 162 /// ModuleBitcodeWriter and ThinLinkBitcodeWriter. 163 class ModuleBitcodeWriterBase : public BitcodeWriterBase { 164 protected: 165 /// The Module to write to bitcode. 166 const Module &M; 167 168 /// Enumerates ids for all values in the module. 169 ValueEnumerator VE; 170 171 /// Optional per-module index to write for ThinLTO. 172 const ModuleSummaryIndex *Index; 173 174 /// Map that holds the correspondence between GUIDs in the summary index, 175 /// that came from indirect call profiles, and a value id generated by this 176 /// class to use in the VST and summary block records. 177 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap; 178 179 /// Tracks the last value id recorded in the GUIDToValueMap. 180 unsigned GlobalValueId; 181 182 /// Saves the offset of the VSTOffset record that must eventually be 183 /// backpatched with the offset of the actual VST. 184 uint64_t VSTOffsetPlaceholder = 0; 185 186 public: 187 /// Constructs a ModuleBitcodeWriterBase object for the given Module, 188 /// writing to the provided \p Buffer. 189 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder, 190 BitstreamWriter &Stream, 191 bool ShouldPreserveUseListOrder, 192 const ModuleSummaryIndex *Index) 193 : BitcodeWriterBase(Stream, StrtabBuilder), M(M), 194 VE(M, ShouldPreserveUseListOrder), Index(Index) { 195 // Assign ValueIds to any callee values in the index that came from 196 // indirect call profiles and were recorded as a GUID not a Value* 197 // (which would have been assigned an ID by the ValueEnumerator). 198 // The starting ValueId is just after the number of values in the 199 // ValueEnumerator, so that they can be emitted in the VST. 200 GlobalValueId = VE.getValues().size(); 201 if (!Index) 202 return; 203 for (const auto &GUIDSummaryLists : *Index) 204 // Examine all summaries for this GUID. 205 for (auto &Summary : GUIDSummaryLists.second.SummaryList) 206 if (auto FS = dyn_cast<FunctionSummary>(Summary.get())) 207 // For each call in the function summary, see if the call 208 // is to a GUID (which means it is for an indirect call, 209 // otherwise we would have a Value for it). If so, synthesize 210 // a value id. 211 for (auto &CallEdge : FS->calls()) 212 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue()) 213 assignValueId(CallEdge.first.getGUID()); 214 } 215 216 protected: 217 void writePerModuleGlobalValueSummary(); 218 219 private: 220 void writePerModuleFunctionSummaryRecord( 221 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary, 222 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev, 223 unsigned CallsiteAbbrev, unsigned AllocAbbrev, const Function &F); 224 void writeModuleLevelReferences(const GlobalVariable &V, 225 SmallVector<uint64_t, 64> &NameVals, 226 unsigned FSModRefsAbbrev, 227 unsigned FSModVTableRefsAbbrev); 228 229 void assignValueId(GlobalValue::GUID ValGUID) { 230 GUIDToValueIdMap[ValGUID] = ++GlobalValueId; 231 } 232 233 unsigned getValueId(GlobalValue::GUID ValGUID) { 234 const auto &VMI = GUIDToValueIdMap.find(ValGUID); 235 // Expect that any GUID value had a value Id assigned by an 236 // earlier call to assignValueId. 237 assert(VMI != GUIDToValueIdMap.end() && 238 "GUID does not have assigned value Id"); 239 return VMI->second; 240 } 241 242 // Helper to get the valueId for the type of value recorded in VI. 243 unsigned getValueId(ValueInfo VI) { 244 if (!VI.haveGVs() || !VI.getValue()) 245 return getValueId(VI.getGUID()); 246 return VE.getValueID(VI.getValue()); 247 } 248 249 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; } 250 }; 251 252 /// Class to manage the bitcode writing for a module. 253 class ModuleBitcodeWriter : public ModuleBitcodeWriterBase { 254 /// Pointer to the buffer allocated by caller for bitcode writing. 255 const SmallVectorImpl<char> &Buffer; 256 257 /// True if a module hash record should be written. 258 bool GenerateHash; 259 260 /// If non-null, when GenerateHash is true, the resulting hash is written 261 /// into ModHash. 262 ModuleHash *ModHash; 263 264 SHA1 Hasher; 265 266 /// The start bit of the identification block. 267 uint64_t BitcodeStartBit; 268 269 public: 270 /// Constructs a ModuleBitcodeWriter object for the given Module, 271 /// writing to the provided \p Buffer. 272 ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer, 273 StringTableBuilder &StrtabBuilder, 274 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder, 275 const ModuleSummaryIndex *Index, bool GenerateHash, 276 ModuleHash *ModHash = nullptr) 277 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream, 278 ShouldPreserveUseListOrder, Index), 279 Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash), 280 BitcodeStartBit(Stream.GetCurrentBitNo()) {} 281 282 /// Emit the current module to the bitstream. 283 void write(); 284 285 private: 286 uint64_t bitcodeStartBit() { return BitcodeStartBit; } 287 288 size_t addToStrtab(StringRef Str); 289 290 void writeAttributeGroupTable(); 291 void writeAttributeTable(); 292 void writeTypeTable(); 293 void writeComdats(); 294 void writeValueSymbolTableForwardDecl(); 295 void writeModuleInfo(); 296 void writeValueAsMetadata(const ValueAsMetadata *MD, 297 SmallVectorImpl<uint64_t> &Record); 298 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record, 299 unsigned Abbrev); 300 unsigned createDILocationAbbrev(); 301 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record, 302 unsigned &Abbrev); 303 unsigned createGenericDINodeAbbrev(); 304 void writeGenericDINode(const GenericDINode *N, 305 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev); 306 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record, 307 unsigned Abbrev); 308 void writeDIGenericSubrange(const DIGenericSubrange *N, 309 SmallVectorImpl<uint64_t> &Record, 310 unsigned Abbrev); 311 void writeDIEnumerator(const DIEnumerator *N, 312 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 313 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record, 314 unsigned Abbrev); 315 void writeDIStringType(const DIStringType *N, 316 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 317 void writeDIDerivedType(const DIDerivedType *N, 318 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 319 void writeDICompositeType(const DICompositeType *N, 320 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 321 void writeDISubroutineType(const DISubroutineType *N, 322 SmallVectorImpl<uint64_t> &Record, 323 unsigned Abbrev); 324 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record, 325 unsigned Abbrev); 326 void writeDICompileUnit(const DICompileUnit *N, 327 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 328 void writeDISubprogram(const DISubprogram *N, 329 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 330 void writeDILexicalBlock(const DILexicalBlock *N, 331 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 332 void writeDILexicalBlockFile(const DILexicalBlockFile *N, 333 SmallVectorImpl<uint64_t> &Record, 334 unsigned Abbrev); 335 void writeDICommonBlock(const DICommonBlock *N, 336 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 337 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record, 338 unsigned Abbrev); 339 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record, 340 unsigned Abbrev); 341 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record, 342 unsigned Abbrev); 343 void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record); 344 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record, 345 unsigned Abbrev); 346 void writeDIAssignID(const DIAssignID *N, SmallVectorImpl<uint64_t> &Record, 347 unsigned Abbrev); 348 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N, 349 SmallVectorImpl<uint64_t> &Record, 350 unsigned Abbrev); 351 void writeDITemplateValueParameter(const DITemplateValueParameter *N, 352 SmallVectorImpl<uint64_t> &Record, 353 unsigned Abbrev); 354 void writeDIGlobalVariable(const DIGlobalVariable *N, 355 SmallVectorImpl<uint64_t> &Record, 356 unsigned Abbrev); 357 void writeDILocalVariable(const DILocalVariable *N, 358 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 359 void writeDILabel(const DILabel *N, 360 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 361 void writeDIExpression(const DIExpression *N, 362 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 363 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N, 364 SmallVectorImpl<uint64_t> &Record, 365 unsigned Abbrev); 366 void writeDIObjCProperty(const DIObjCProperty *N, 367 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 368 void writeDIImportedEntity(const DIImportedEntity *N, 369 SmallVectorImpl<uint64_t> &Record, 370 unsigned Abbrev); 371 unsigned createNamedMetadataAbbrev(); 372 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record); 373 unsigned createMetadataStringsAbbrev(); 374 void writeMetadataStrings(ArrayRef<const Metadata *> Strings, 375 SmallVectorImpl<uint64_t> &Record); 376 void writeMetadataRecords(ArrayRef<const Metadata *> MDs, 377 SmallVectorImpl<uint64_t> &Record, 378 std::vector<unsigned> *MDAbbrevs = nullptr, 379 std::vector<uint64_t> *IndexPos = nullptr); 380 void writeModuleMetadata(); 381 void writeFunctionMetadata(const Function &F); 382 void writeFunctionMetadataAttachment(const Function &F); 383 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record, 384 const GlobalObject &GO); 385 void writeModuleMetadataKinds(); 386 void writeOperandBundleTags(); 387 void writeSyncScopeNames(); 388 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal); 389 void writeModuleConstants(); 390 bool pushValueAndType(const Value *V, unsigned InstID, 391 SmallVectorImpl<unsigned> &Vals); 392 void writeOperandBundles(const CallBase &CB, unsigned InstID); 393 void pushValue(const Value *V, unsigned InstID, 394 SmallVectorImpl<unsigned> &Vals); 395 void pushValueSigned(const Value *V, unsigned InstID, 396 SmallVectorImpl<uint64_t> &Vals); 397 void writeInstruction(const Instruction &I, unsigned InstID, 398 SmallVectorImpl<unsigned> &Vals); 399 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST); 400 void writeGlobalValueSymbolTable( 401 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex); 402 void writeUseList(UseListOrder &&Order); 403 void writeUseListBlock(const Function *F); 404 void 405 writeFunction(const Function &F, 406 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex); 407 void writeBlockInfo(); 408 void writeModuleHash(size_t BlockStartPos); 409 410 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) { 411 return unsigned(SSID); 412 } 413 414 unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); } 415 }; 416 417 /// Class to manage the bitcode writing for a combined index. 418 class IndexBitcodeWriter : public BitcodeWriterBase { 419 /// The combined index to write to bitcode. 420 const ModuleSummaryIndex &Index; 421 422 /// When writing a subset of the index for distributed backends, client 423 /// provides a map of modules to the corresponding GUIDs/summaries to write. 424 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex; 425 426 /// Map that holds the correspondence between the GUID used in the combined 427 /// index and a value id generated by this class to use in references. 428 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap; 429 430 // The sorted stack id indices actually used in the summary entries being 431 // written, which will be a subset of those in the full index in the case of 432 // distributed indexes. 433 std::vector<unsigned> StackIdIndices; 434 435 /// Tracks the last value id recorded in the GUIDToValueMap. 436 unsigned GlobalValueId = 0; 437 438 /// Tracks the assignment of module paths in the module path string table to 439 /// an id assigned for use in summary references to the module path. 440 DenseMap<StringRef, uint64_t> ModuleIdMap; 441 442 public: 443 /// Constructs a IndexBitcodeWriter object for the given combined index, 444 /// writing to the provided \p Buffer. When writing a subset of the index 445 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map. 446 IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder, 447 const ModuleSummaryIndex &Index, 448 const std::map<std::string, GVSummaryMapTy> 449 *ModuleToSummariesForIndex = nullptr) 450 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index), 451 ModuleToSummariesForIndex(ModuleToSummariesForIndex) { 452 // Assign unique value ids to all summaries to be written, for use 453 // in writing out the call graph edges. Save the mapping from GUID 454 // to the new global value id to use when writing those edges, which 455 // are currently saved in the index in terms of GUID. 456 forEachSummary([&](GVInfo I, bool IsAliasee) { 457 GUIDToValueIdMap[I.first] = ++GlobalValueId; 458 if (IsAliasee) 459 return; 460 auto *FS = dyn_cast<FunctionSummary>(I.second); 461 if (!FS) 462 return; 463 // Record all stack id indices actually used in the summary entries being 464 // written, so that we can compact them in the case of distributed ThinLTO 465 // indexes. 466 for (auto &CI : FS->callsites()) { 467 // If the stack id list is empty, this callsite info was synthesized for 468 // a missing tail call frame. Ensure that the callee's GUID gets a value 469 // id. Normally we only generate these for defined summaries, which in 470 // the case of distributed ThinLTO is only the functions already defined 471 // in the module or that we want to import. We don't bother to include 472 // all the callee symbols as they aren't normally needed in the backend. 473 // However, for the synthesized callsite infos we do need the callee 474 // GUID in the backend so that we can correlate the identified callee 475 // with this callsite info (which for non-tail calls is done by the 476 // ordering of the callsite infos and verified via stack ids). 477 if (CI.StackIdIndices.empty()) { 478 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId; 479 continue; 480 } 481 for (auto Idx : CI.StackIdIndices) 482 StackIdIndices.push_back(Idx); 483 } 484 for (auto &AI : FS->allocs()) 485 for (auto &MIB : AI.MIBs) 486 for (auto Idx : MIB.StackIdIndices) 487 StackIdIndices.push_back(Idx); 488 }); 489 llvm::sort(StackIdIndices); 490 StackIdIndices.erase( 491 std::unique(StackIdIndices.begin(), StackIdIndices.end()), 492 StackIdIndices.end()); 493 } 494 495 /// The below iterator returns the GUID and associated summary. 496 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>; 497 498 /// Calls the callback for each value GUID and summary to be written to 499 /// bitcode. This hides the details of whether they are being pulled from the 500 /// entire index or just those in a provided ModuleToSummariesForIndex map. 501 template<typename Functor> 502 void forEachSummary(Functor Callback) { 503 if (ModuleToSummariesForIndex) { 504 for (auto &M : *ModuleToSummariesForIndex) 505 for (auto &Summary : M.second) { 506 Callback(Summary, false); 507 // Ensure aliasee is handled, e.g. for assigning a valueId, 508 // even if we are not importing the aliasee directly (the 509 // imported alias will contain a copy of aliasee). 510 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond())) 511 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true); 512 } 513 } else { 514 for (auto &Summaries : Index) 515 for (auto &Summary : Summaries.second.SummaryList) 516 Callback({Summaries.first, Summary.get()}, false); 517 } 518 } 519 520 /// Calls the callback for each entry in the modulePaths StringMap that 521 /// should be written to the module path string table. This hides the details 522 /// of whether they are being pulled from the entire index or just those in a 523 /// provided ModuleToSummariesForIndex map. 524 template <typename Functor> void forEachModule(Functor Callback) { 525 if (ModuleToSummariesForIndex) { 526 for (const auto &M : *ModuleToSummariesForIndex) { 527 const auto &MPI = Index.modulePaths().find(M.first); 528 if (MPI == Index.modulePaths().end()) { 529 // This should only happen if the bitcode file was empty, in which 530 // case we shouldn't be importing (the ModuleToSummariesForIndex 531 // would only include the module we are writing and index for). 532 assert(ModuleToSummariesForIndex->size() == 1); 533 continue; 534 } 535 Callback(*MPI); 536 } 537 } else { 538 // Since StringMap iteration order isn't guaranteed, order by path string 539 // first. 540 // FIXME: Make this a vector of StringMapEntry instead to avoid the later 541 // map lookup. 542 std::vector<StringRef> ModulePaths; 543 for (auto &[ModPath, _] : Index.modulePaths()) 544 ModulePaths.push_back(ModPath); 545 llvm::sort(ModulePaths.begin(), ModulePaths.end()); 546 for (auto &ModPath : ModulePaths) 547 Callback(*Index.modulePaths().find(ModPath)); 548 } 549 } 550 551 /// Main entry point for writing a combined index to bitcode. 552 void write(); 553 554 private: 555 void writeModStrings(); 556 void writeCombinedGlobalValueSummary(); 557 558 std::optional<unsigned> getValueId(GlobalValue::GUID ValGUID) { 559 auto VMI = GUIDToValueIdMap.find(ValGUID); 560 if (VMI == GUIDToValueIdMap.end()) 561 return std::nullopt; 562 return VMI->second; 563 } 564 565 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; } 566 }; 567 568 } // end anonymous namespace 569 570 static unsigned getEncodedCastOpcode(unsigned Opcode) { 571 switch (Opcode) { 572 default: llvm_unreachable("Unknown cast instruction!"); 573 case Instruction::Trunc : return bitc::CAST_TRUNC; 574 case Instruction::ZExt : return bitc::CAST_ZEXT; 575 case Instruction::SExt : return bitc::CAST_SEXT; 576 case Instruction::FPToUI : return bitc::CAST_FPTOUI; 577 case Instruction::FPToSI : return bitc::CAST_FPTOSI; 578 case Instruction::UIToFP : return bitc::CAST_UITOFP; 579 case Instruction::SIToFP : return bitc::CAST_SITOFP; 580 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC; 581 case Instruction::FPExt : return bitc::CAST_FPEXT; 582 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT; 583 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR; 584 case Instruction::BitCast : return bitc::CAST_BITCAST; 585 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST; 586 } 587 } 588 589 static unsigned getEncodedUnaryOpcode(unsigned Opcode) { 590 switch (Opcode) { 591 default: llvm_unreachable("Unknown binary instruction!"); 592 case Instruction::FNeg: return bitc::UNOP_FNEG; 593 } 594 } 595 596 static unsigned getEncodedBinaryOpcode(unsigned Opcode) { 597 switch (Opcode) { 598 default: llvm_unreachable("Unknown binary instruction!"); 599 case Instruction::Add: 600 case Instruction::FAdd: return bitc::BINOP_ADD; 601 case Instruction::Sub: 602 case Instruction::FSub: return bitc::BINOP_SUB; 603 case Instruction::Mul: 604 case Instruction::FMul: return bitc::BINOP_MUL; 605 case Instruction::UDiv: return bitc::BINOP_UDIV; 606 case Instruction::FDiv: 607 case Instruction::SDiv: return bitc::BINOP_SDIV; 608 case Instruction::URem: return bitc::BINOP_UREM; 609 case Instruction::FRem: 610 case Instruction::SRem: return bitc::BINOP_SREM; 611 case Instruction::Shl: return bitc::BINOP_SHL; 612 case Instruction::LShr: return bitc::BINOP_LSHR; 613 case Instruction::AShr: return bitc::BINOP_ASHR; 614 case Instruction::And: return bitc::BINOP_AND; 615 case Instruction::Or: return bitc::BINOP_OR; 616 case Instruction::Xor: return bitc::BINOP_XOR; 617 } 618 } 619 620 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) { 621 switch (Op) { 622 default: llvm_unreachable("Unknown RMW operation!"); 623 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG; 624 case AtomicRMWInst::Add: return bitc::RMW_ADD; 625 case AtomicRMWInst::Sub: return bitc::RMW_SUB; 626 case AtomicRMWInst::And: return bitc::RMW_AND; 627 case AtomicRMWInst::Nand: return bitc::RMW_NAND; 628 case AtomicRMWInst::Or: return bitc::RMW_OR; 629 case AtomicRMWInst::Xor: return bitc::RMW_XOR; 630 case AtomicRMWInst::Max: return bitc::RMW_MAX; 631 case AtomicRMWInst::Min: return bitc::RMW_MIN; 632 case AtomicRMWInst::UMax: return bitc::RMW_UMAX; 633 case AtomicRMWInst::UMin: return bitc::RMW_UMIN; 634 case AtomicRMWInst::FAdd: return bitc::RMW_FADD; 635 case AtomicRMWInst::FSub: return bitc::RMW_FSUB; 636 case AtomicRMWInst::FMax: return bitc::RMW_FMAX; 637 case AtomicRMWInst::FMin: return bitc::RMW_FMIN; 638 case AtomicRMWInst::UIncWrap: 639 return bitc::RMW_UINC_WRAP; 640 case AtomicRMWInst::UDecWrap: 641 return bitc::RMW_UDEC_WRAP; 642 } 643 } 644 645 static unsigned getEncodedOrdering(AtomicOrdering Ordering) { 646 switch (Ordering) { 647 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC; 648 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED; 649 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC; 650 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE; 651 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE; 652 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL; 653 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST; 654 } 655 llvm_unreachable("Invalid ordering"); 656 } 657 658 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, 659 StringRef Str, unsigned AbbrevToUse) { 660 SmallVector<unsigned, 64> Vals; 661 662 // Code: [strchar x N] 663 for (char C : Str) { 664 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C)) 665 AbbrevToUse = 0; 666 Vals.push_back(C); 667 } 668 669 // Emit the finished record. 670 Stream.EmitRecord(Code, Vals, AbbrevToUse); 671 } 672 673 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) { 674 switch (Kind) { 675 case Attribute::Alignment: 676 return bitc::ATTR_KIND_ALIGNMENT; 677 case Attribute::AllocAlign: 678 return bitc::ATTR_KIND_ALLOC_ALIGN; 679 case Attribute::AllocSize: 680 return bitc::ATTR_KIND_ALLOC_SIZE; 681 case Attribute::AlwaysInline: 682 return bitc::ATTR_KIND_ALWAYS_INLINE; 683 case Attribute::Builtin: 684 return bitc::ATTR_KIND_BUILTIN; 685 case Attribute::ByVal: 686 return bitc::ATTR_KIND_BY_VAL; 687 case Attribute::Convergent: 688 return bitc::ATTR_KIND_CONVERGENT; 689 case Attribute::InAlloca: 690 return bitc::ATTR_KIND_IN_ALLOCA; 691 case Attribute::Cold: 692 return bitc::ATTR_KIND_COLD; 693 case Attribute::DisableSanitizerInstrumentation: 694 return bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION; 695 case Attribute::FnRetThunkExtern: 696 return bitc::ATTR_KIND_FNRETTHUNK_EXTERN; 697 case Attribute::Hot: 698 return bitc::ATTR_KIND_HOT; 699 case Attribute::ElementType: 700 return bitc::ATTR_KIND_ELEMENTTYPE; 701 case Attribute::InlineHint: 702 return bitc::ATTR_KIND_INLINE_HINT; 703 case Attribute::InReg: 704 return bitc::ATTR_KIND_IN_REG; 705 case Attribute::JumpTable: 706 return bitc::ATTR_KIND_JUMP_TABLE; 707 case Attribute::MinSize: 708 return bitc::ATTR_KIND_MIN_SIZE; 709 case Attribute::AllocatedPointer: 710 return bitc::ATTR_KIND_ALLOCATED_POINTER; 711 case Attribute::AllocKind: 712 return bitc::ATTR_KIND_ALLOC_KIND; 713 case Attribute::Memory: 714 return bitc::ATTR_KIND_MEMORY; 715 case Attribute::NoFPClass: 716 return bitc::ATTR_KIND_NOFPCLASS; 717 case Attribute::Naked: 718 return bitc::ATTR_KIND_NAKED; 719 case Attribute::Nest: 720 return bitc::ATTR_KIND_NEST; 721 case Attribute::NoAlias: 722 return bitc::ATTR_KIND_NO_ALIAS; 723 case Attribute::NoBuiltin: 724 return bitc::ATTR_KIND_NO_BUILTIN; 725 case Attribute::NoCallback: 726 return bitc::ATTR_KIND_NO_CALLBACK; 727 case Attribute::NoCapture: 728 return bitc::ATTR_KIND_NO_CAPTURE; 729 case Attribute::NoDuplicate: 730 return bitc::ATTR_KIND_NO_DUPLICATE; 731 case Attribute::NoFree: 732 return bitc::ATTR_KIND_NOFREE; 733 case Attribute::NoImplicitFloat: 734 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT; 735 case Attribute::NoInline: 736 return bitc::ATTR_KIND_NO_INLINE; 737 case Attribute::NoRecurse: 738 return bitc::ATTR_KIND_NO_RECURSE; 739 case Attribute::NoMerge: 740 return bitc::ATTR_KIND_NO_MERGE; 741 case Attribute::NonLazyBind: 742 return bitc::ATTR_KIND_NON_LAZY_BIND; 743 case Attribute::NonNull: 744 return bitc::ATTR_KIND_NON_NULL; 745 case Attribute::Dereferenceable: 746 return bitc::ATTR_KIND_DEREFERENCEABLE; 747 case Attribute::DereferenceableOrNull: 748 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL; 749 case Attribute::NoRedZone: 750 return bitc::ATTR_KIND_NO_RED_ZONE; 751 case Attribute::NoReturn: 752 return bitc::ATTR_KIND_NO_RETURN; 753 case Attribute::NoSync: 754 return bitc::ATTR_KIND_NOSYNC; 755 case Attribute::NoCfCheck: 756 return bitc::ATTR_KIND_NOCF_CHECK; 757 case Attribute::NoProfile: 758 return bitc::ATTR_KIND_NO_PROFILE; 759 case Attribute::SkipProfile: 760 return bitc::ATTR_KIND_SKIP_PROFILE; 761 case Attribute::NoUnwind: 762 return bitc::ATTR_KIND_NO_UNWIND; 763 case Attribute::NoSanitizeBounds: 764 return bitc::ATTR_KIND_NO_SANITIZE_BOUNDS; 765 case Attribute::NoSanitizeCoverage: 766 return bitc::ATTR_KIND_NO_SANITIZE_COVERAGE; 767 case Attribute::NullPointerIsValid: 768 return bitc::ATTR_KIND_NULL_POINTER_IS_VALID; 769 case Attribute::OptimizeForDebugging: 770 return bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING; 771 case Attribute::OptForFuzzing: 772 return bitc::ATTR_KIND_OPT_FOR_FUZZING; 773 case Attribute::OptimizeForSize: 774 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE; 775 case Attribute::OptimizeNone: 776 return bitc::ATTR_KIND_OPTIMIZE_NONE; 777 case Attribute::ReadNone: 778 return bitc::ATTR_KIND_READ_NONE; 779 case Attribute::ReadOnly: 780 return bitc::ATTR_KIND_READ_ONLY; 781 case Attribute::Returned: 782 return bitc::ATTR_KIND_RETURNED; 783 case Attribute::ReturnsTwice: 784 return bitc::ATTR_KIND_RETURNS_TWICE; 785 case Attribute::SExt: 786 return bitc::ATTR_KIND_S_EXT; 787 case Attribute::Speculatable: 788 return bitc::ATTR_KIND_SPECULATABLE; 789 case Attribute::StackAlignment: 790 return bitc::ATTR_KIND_STACK_ALIGNMENT; 791 case Attribute::StackProtect: 792 return bitc::ATTR_KIND_STACK_PROTECT; 793 case Attribute::StackProtectReq: 794 return bitc::ATTR_KIND_STACK_PROTECT_REQ; 795 case Attribute::StackProtectStrong: 796 return bitc::ATTR_KIND_STACK_PROTECT_STRONG; 797 case Attribute::SafeStack: 798 return bitc::ATTR_KIND_SAFESTACK; 799 case Attribute::ShadowCallStack: 800 return bitc::ATTR_KIND_SHADOWCALLSTACK; 801 case Attribute::StrictFP: 802 return bitc::ATTR_KIND_STRICT_FP; 803 case Attribute::StructRet: 804 return bitc::ATTR_KIND_STRUCT_RET; 805 case Attribute::SanitizeAddress: 806 return bitc::ATTR_KIND_SANITIZE_ADDRESS; 807 case Attribute::SanitizeHWAddress: 808 return bitc::ATTR_KIND_SANITIZE_HWADDRESS; 809 case Attribute::SanitizeThread: 810 return bitc::ATTR_KIND_SANITIZE_THREAD; 811 case Attribute::SanitizeMemory: 812 return bitc::ATTR_KIND_SANITIZE_MEMORY; 813 case Attribute::SpeculativeLoadHardening: 814 return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING; 815 case Attribute::SwiftError: 816 return bitc::ATTR_KIND_SWIFT_ERROR; 817 case Attribute::SwiftSelf: 818 return bitc::ATTR_KIND_SWIFT_SELF; 819 case Attribute::SwiftAsync: 820 return bitc::ATTR_KIND_SWIFT_ASYNC; 821 case Attribute::UWTable: 822 return bitc::ATTR_KIND_UW_TABLE; 823 case Attribute::VScaleRange: 824 return bitc::ATTR_KIND_VSCALE_RANGE; 825 case Attribute::WillReturn: 826 return bitc::ATTR_KIND_WILLRETURN; 827 case Attribute::WriteOnly: 828 return bitc::ATTR_KIND_WRITEONLY; 829 case Attribute::ZExt: 830 return bitc::ATTR_KIND_Z_EXT; 831 case Attribute::ImmArg: 832 return bitc::ATTR_KIND_IMMARG; 833 case Attribute::SanitizeMemTag: 834 return bitc::ATTR_KIND_SANITIZE_MEMTAG; 835 case Attribute::Preallocated: 836 return bitc::ATTR_KIND_PREALLOCATED; 837 case Attribute::NoUndef: 838 return bitc::ATTR_KIND_NOUNDEF; 839 case Attribute::ByRef: 840 return bitc::ATTR_KIND_BYREF; 841 case Attribute::MustProgress: 842 return bitc::ATTR_KIND_MUSTPROGRESS; 843 case Attribute::PresplitCoroutine: 844 return bitc::ATTR_KIND_PRESPLIT_COROUTINE; 845 case Attribute::Writable: 846 return bitc::ATTR_KIND_WRITABLE; 847 case Attribute::CoroDestroyOnlyWhenComplete: 848 return bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE; 849 case Attribute::DeadOnUnwind: 850 return bitc::ATTR_KIND_DEAD_ON_UNWIND; 851 case Attribute::Range: 852 return bitc::ATTR_KIND_RANGE; 853 case Attribute::EndAttrKinds: 854 llvm_unreachable("Can not encode end-attribute kinds marker."); 855 case Attribute::None: 856 llvm_unreachable("Can not encode none-attribute."); 857 case Attribute::EmptyKey: 858 case Attribute::TombstoneKey: 859 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey"); 860 } 861 862 llvm_unreachable("Trying to encode unknown attribute"); 863 } 864 865 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) { 866 if ((int64_t)V >= 0) 867 Vals.push_back(V << 1); 868 else 869 Vals.push_back((-V << 1) | 1); 870 } 871 872 static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) { 873 // We have an arbitrary precision integer value to write whose 874 // bit width is > 64. However, in canonical unsigned integer 875 // format it is likely that the high bits are going to be zero. 876 // So, we only write the number of active words. 877 unsigned NumWords = A.getActiveWords(); 878 const uint64_t *RawData = A.getRawData(); 879 for (unsigned i = 0; i < NumWords; i++) 880 emitSignedInt64(Vals, RawData[i]); 881 } 882 883 static void emitConstantRange(SmallVectorImpl<uint64_t> &Record, 884 const ConstantRange &CR) { 885 unsigned BitWidth = CR.getBitWidth(); 886 Record.push_back(BitWidth); 887 if (BitWidth > 64) { 888 Record.push_back(CR.getLower().getActiveWords() | 889 (uint64_t(CR.getUpper().getActiveWords()) << 32)); 890 emitWideAPInt(Record, CR.getLower()); 891 emitWideAPInt(Record, CR.getUpper()); 892 } else { 893 emitSignedInt64(Record, CR.getLower().getSExtValue()); 894 emitSignedInt64(Record, CR.getUpper().getSExtValue()); 895 } 896 } 897 898 void ModuleBitcodeWriter::writeAttributeGroupTable() { 899 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps = 900 VE.getAttributeGroups(); 901 if (AttrGrps.empty()) return; 902 903 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3); 904 905 SmallVector<uint64_t, 64> Record; 906 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) { 907 unsigned AttrListIndex = Pair.first; 908 AttributeSet AS = Pair.second; 909 Record.push_back(VE.getAttributeGroupID(Pair)); 910 Record.push_back(AttrListIndex); 911 912 for (Attribute Attr : AS) { 913 if (Attr.isEnumAttribute()) { 914 Record.push_back(0); 915 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 916 } else if (Attr.isIntAttribute()) { 917 Record.push_back(1); 918 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 919 Record.push_back(Attr.getValueAsInt()); 920 } else if (Attr.isStringAttribute()) { 921 StringRef Kind = Attr.getKindAsString(); 922 StringRef Val = Attr.getValueAsString(); 923 924 Record.push_back(Val.empty() ? 3 : 4); 925 Record.append(Kind.begin(), Kind.end()); 926 Record.push_back(0); 927 if (!Val.empty()) { 928 Record.append(Val.begin(), Val.end()); 929 Record.push_back(0); 930 } 931 } else if (Attr.isTypeAttribute()) { 932 Type *Ty = Attr.getValueAsType(); 933 Record.push_back(Ty ? 6 : 5); 934 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 935 if (Ty) 936 Record.push_back(VE.getTypeID(Attr.getValueAsType())); 937 } else { 938 assert(Attr.isConstantRangeAttribute()); 939 Record.push_back(7); 940 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 941 emitConstantRange(Record, Attr.getValueAsConstantRange()); 942 } 943 } 944 945 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record); 946 Record.clear(); 947 } 948 949 Stream.ExitBlock(); 950 } 951 952 void ModuleBitcodeWriter::writeAttributeTable() { 953 const std::vector<AttributeList> &Attrs = VE.getAttributeLists(); 954 if (Attrs.empty()) return; 955 956 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3); 957 958 SmallVector<uint64_t, 64> Record; 959 for (const AttributeList &AL : Attrs) { 960 for (unsigned i : AL.indexes()) { 961 AttributeSet AS = AL.getAttributes(i); 962 if (AS.hasAttributes()) 963 Record.push_back(VE.getAttributeGroupID({i, AS})); 964 } 965 966 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record); 967 Record.clear(); 968 } 969 970 Stream.ExitBlock(); 971 } 972 973 /// WriteTypeTable - Write out the type table for a module. 974 void ModuleBitcodeWriter::writeTypeTable() { 975 const ValueEnumerator::TypeList &TypeList = VE.getTypes(); 976 977 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */); 978 SmallVector<uint64_t, 64> TypeVals; 979 980 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies(); 981 982 // Abbrev for TYPE_CODE_OPAQUE_POINTER. 983 auto Abbv = std::make_shared<BitCodeAbbrev>(); 984 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_OPAQUE_POINTER)); 985 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0 986 unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 987 988 // Abbrev for TYPE_CODE_FUNCTION. 989 Abbv = std::make_shared<BitCodeAbbrev>(); 990 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION)); 991 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg 992 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 993 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 994 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 995 996 // Abbrev for TYPE_CODE_STRUCT_ANON. 997 Abbv = std::make_shared<BitCodeAbbrev>(); 998 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON)); 999 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 1000 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1001 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 1002 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1003 1004 // Abbrev for TYPE_CODE_STRUCT_NAME. 1005 Abbv = std::make_shared<BitCodeAbbrev>(); 1006 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME)); 1007 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1008 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1009 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1010 1011 // Abbrev for TYPE_CODE_STRUCT_NAMED. 1012 Abbv = std::make_shared<BitCodeAbbrev>(); 1013 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED)); 1014 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 1015 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1016 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 1017 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1018 1019 // Abbrev for TYPE_CODE_ARRAY. 1020 Abbv = std::make_shared<BitCodeAbbrev>(); 1021 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY)); 1022 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size 1023 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 1024 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1025 1026 // Emit an entry count so the reader can reserve space. 1027 TypeVals.push_back(TypeList.size()); 1028 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals); 1029 TypeVals.clear(); 1030 1031 // Loop over all of the types, emitting each in turn. 1032 for (Type *T : TypeList) { 1033 int AbbrevToUse = 0; 1034 unsigned Code = 0; 1035 1036 switch (T->getTypeID()) { 1037 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break; 1038 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break; 1039 case Type::BFloatTyID: Code = bitc::TYPE_CODE_BFLOAT; break; 1040 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break; 1041 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break; 1042 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break; 1043 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break; 1044 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break; 1045 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break; 1046 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break; 1047 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break; 1048 case Type::X86_AMXTyID: Code = bitc::TYPE_CODE_X86_AMX; break; 1049 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break; 1050 case Type::IntegerTyID: 1051 // INTEGER: [width] 1052 Code = bitc::TYPE_CODE_INTEGER; 1053 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 1054 break; 1055 case Type::PointerTyID: { 1056 PointerType *PTy = cast<PointerType>(T); 1057 unsigned AddressSpace = PTy->getAddressSpace(); 1058 // OPAQUE_POINTER: [address space] 1059 Code = bitc::TYPE_CODE_OPAQUE_POINTER; 1060 TypeVals.push_back(AddressSpace); 1061 if (AddressSpace == 0) 1062 AbbrevToUse = OpaquePtrAbbrev; 1063 break; 1064 } 1065 case Type::FunctionTyID: { 1066 FunctionType *FT = cast<FunctionType>(T); 1067 // FUNCTION: [isvararg, retty, paramty x N] 1068 Code = bitc::TYPE_CODE_FUNCTION; 1069 TypeVals.push_back(FT->isVarArg()); 1070 TypeVals.push_back(VE.getTypeID(FT->getReturnType())); 1071 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) 1072 TypeVals.push_back(VE.getTypeID(FT->getParamType(i))); 1073 AbbrevToUse = FunctionAbbrev; 1074 break; 1075 } 1076 case Type::StructTyID: { 1077 StructType *ST = cast<StructType>(T); 1078 // STRUCT: [ispacked, eltty x N] 1079 TypeVals.push_back(ST->isPacked()); 1080 // Output all of the element types. 1081 for (Type *ET : ST->elements()) 1082 TypeVals.push_back(VE.getTypeID(ET)); 1083 1084 if (ST->isLiteral()) { 1085 Code = bitc::TYPE_CODE_STRUCT_ANON; 1086 AbbrevToUse = StructAnonAbbrev; 1087 } else { 1088 if (ST->isOpaque()) { 1089 Code = bitc::TYPE_CODE_OPAQUE; 1090 } else { 1091 Code = bitc::TYPE_CODE_STRUCT_NAMED; 1092 AbbrevToUse = StructNamedAbbrev; 1093 } 1094 1095 // Emit the name if it is present. 1096 if (!ST->getName().empty()) 1097 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(), 1098 StructNameAbbrev); 1099 } 1100 break; 1101 } 1102 case Type::ArrayTyID: { 1103 ArrayType *AT = cast<ArrayType>(T); 1104 // ARRAY: [numelts, eltty] 1105 Code = bitc::TYPE_CODE_ARRAY; 1106 TypeVals.push_back(AT->getNumElements()); 1107 TypeVals.push_back(VE.getTypeID(AT->getElementType())); 1108 AbbrevToUse = ArrayAbbrev; 1109 break; 1110 } 1111 case Type::FixedVectorTyID: 1112 case Type::ScalableVectorTyID: { 1113 VectorType *VT = cast<VectorType>(T); 1114 // VECTOR [numelts, eltty] or 1115 // [numelts, eltty, scalable] 1116 Code = bitc::TYPE_CODE_VECTOR; 1117 TypeVals.push_back(VT->getElementCount().getKnownMinValue()); 1118 TypeVals.push_back(VE.getTypeID(VT->getElementType())); 1119 if (isa<ScalableVectorType>(VT)) 1120 TypeVals.push_back(true); 1121 break; 1122 } 1123 case Type::TargetExtTyID: { 1124 TargetExtType *TET = cast<TargetExtType>(T); 1125 Code = bitc::TYPE_CODE_TARGET_TYPE; 1126 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, TET->getName(), 1127 StructNameAbbrev); 1128 TypeVals.push_back(TET->getNumTypeParameters()); 1129 for (Type *InnerTy : TET->type_params()) 1130 TypeVals.push_back(VE.getTypeID(InnerTy)); 1131 for (unsigned IntParam : TET->int_params()) 1132 TypeVals.push_back(IntParam); 1133 break; 1134 } 1135 case Type::TypedPointerTyID: 1136 llvm_unreachable("Typed pointers cannot be added to IR modules"); 1137 } 1138 1139 // Emit the finished record. 1140 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 1141 TypeVals.clear(); 1142 } 1143 1144 Stream.ExitBlock(); 1145 } 1146 1147 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) { 1148 switch (Linkage) { 1149 case GlobalValue::ExternalLinkage: 1150 return 0; 1151 case GlobalValue::WeakAnyLinkage: 1152 return 16; 1153 case GlobalValue::AppendingLinkage: 1154 return 2; 1155 case GlobalValue::InternalLinkage: 1156 return 3; 1157 case GlobalValue::LinkOnceAnyLinkage: 1158 return 18; 1159 case GlobalValue::ExternalWeakLinkage: 1160 return 7; 1161 case GlobalValue::CommonLinkage: 1162 return 8; 1163 case GlobalValue::PrivateLinkage: 1164 return 9; 1165 case GlobalValue::WeakODRLinkage: 1166 return 17; 1167 case GlobalValue::LinkOnceODRLinkage: 1168 return 19; 1169 case GlobalValue::AvailableExternallyLinkage: 1170 return 12; 1171 } 1172 llvm_unreachable("Invalid linkage"); 1173 } 1174 1175 static unsigned getEncodedLinkage(const GlobalValue &GV) { 1176 return getEncodedLinkage(GV.getLinkage()); 1177 } 1178 1179 static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) { 1180 uint64_t RawFlags = 0; 1181 RawFlags |= Flags.ReadNone; 1182 RawFlags |= (Flags.ReadOnly << 1); 1183 RawFlags |= (Flags.NoRecurse << 2); 1184 RawFlags |= (Flags.ReturnDoesNotAlias << 3); 1185 RawFlags |= (Flags.NoInline << 4); 1186 RawFlags |= (Flags.AlwaysInline << 5); 1187 RawFlags |= (Flags.NoUnwind << 6); 1188 RawFlags |= (Flags.MayThrow << 7); 1189 RawFlags |= (Flags.HasUnknownCall << 8); 1190 RawFlags |= (Flags.MustBeUnreachable << 9); 1191 return RawFlags; 1192 } 1193 1194 // Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags 1195 // in BitcodeReader.cpp. 1196 static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) { 1197 uint64_t RawFlags = 0; 1198 1199 RawFlags |= Flags.NotEligibleToImport; // bool 1200 RawFlags |= (Flags.Live << 1); 1201 RawFlags |= (Flags.DSOLocal << 2); 1202 RawFlags |= (Flags.CanAutoHide << 3); 1203 1204 // Linkage don't need to be remapped at that time for the summary. Any future 1205 // change to the getEncodedLinkage() function will need to be taken into 1206 // account here as well. 1207 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits 1208 1209 RawFlags |= (Flags.Visibility << 8); // 2 bits 1210 1211 return RawFlags; 1212 } 1213 1214 static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) { 1215 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) | 1216 (Flags.Constant << 2) | Flags.VCallVisibility << 3; 1217 return RawFlags; 1218 } 1219 1220 static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI) { 1221 uint64_t RawFlags = 0; 1222 1223 RawFlags |= CI.Hotness; // 3 bits 1224 RawFlags |= (CI.HasTailCall << 3); // 1 bit 1225 1226 return RawFlags; 1227 } 1228 1229 static uint64_t getEncodedRelBFCallEdgeInfo(const CalleeInfo &CI) { 1230 uint64_t RawFlags = 0; 1231 1232 RawFlags |= CI.RelBlockFreq; // CalleeInfo::RelBlockFreqBits bits 1233 RawFlags |= (CI.HasTailCall << CalleeInfo::RelBlockFreqBits); // 1 bit 1234 1235 return RawFlags; 1236 } 1237 1238 static unsigned getEncodedVisibility(const GlobalValue &GV) { 1239 switch (GV.getVisibility()) { 1240 case GlobalValue::DefaultVisibility: return 0; 1241 case GlobalValue::HiddenVisibility: return 1; 1242 case GlobalValue::ProtectedVisibility: return 2; 1243 } 1244 llvm_unreachable("Invalid visibility"); 1245 } 1246 1247 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) { 1248 switch (GV.getDLLStorageClass()) { 1249 case GlobalValue::DefaultStorageClass: return 0; 1250 case GlobalValue::DLLImportStorageClass: return 1; 1251 case GlobalValue::DLLExportStorageClass: return 2; 1252 } 1253 llvm_unreachable("Invalid DLL storage class"); 1254 } 1255 1256 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) { 1257 switch (GV.getThreadLocalMode()) { 1258 case GlobalVariable::NotThreadLocal: return 0; 1259 case GlobalVariable::GeneralDynamicTLSModel: return 1; 1260 case GlobalVariable::LocalDynamicTLSModel: return 2; 1261 case GlobalVariable::InitialExecTLSModel: return 3; 1262 case GlobalVariable::LocalExecTLSModel: return 4; 1263 } 1264 llvm_unreachable("Invalid TLS model"); 1265 } 1266 1267 static unsigned getEncodedComdatSelectionKind(const Comdat &C) { 1268 switch (C.getSelectionKind()) { 1269 case Comdat::Any: 1270 return bitc::COMDAT_SELECTION_KIND_ANY; 1271 case Comdat::ExactMatch: 1272 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH; 1273 case Comdat::Largest: 1274 return bitc::COMDAT_SELECTION_KIND_LARGEST; 1275 case Comdat::NoDeduplicate: 1276 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES; 1277 case Comdat::SameSize: 1278 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE; 1279 } 1280 llvm_unreachable("Invalid selection kind"); 1281 } 1282 1283 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) { 1284 switch (GV.getUnnamedAddr()) { 1285 case GlobalValue::UnnamedAddr::None: return 0; 1286 case GlobalValue::UnnamedAddr::Local: return 2; 1287 case GlobalValue::UnnamedAddr::Global: return 1; 1288 } 1289 llvm_unreachable("Invalid unnamed_addr"); 1290 } 1291 1292 size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) { 1293 if (GenerateHash) 1294 Hasher.update(Str); 1295 return StrtabBuilder.add(Str); 1296 } 1297 1298 void ModuleBitcodeWriter::writeComdats() { 1299 SmallVector<unsigned, 64> Vals; 1300 for (const Comdat *C : VE.getComdats()) { 1301 // COMDAT: [strtab offset, strtab size, selection_kind] 1302 Vals.push_back(addToStrtab(C->getName())); 1303 Vals.push_back(C->getName().size()); 1304 Vals.push_back(getEncodedComdatSelectionKind(*C)); 1305 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0); 1306 Vals.clear(); 1307 } 1308 } 1309 1310 /// Write a record that will eventually hold the word offset of the 1311 /// module-level VST. For now the offset is 0, which will be backpatched 1312 /// after the real VST is written. Saves the bit offset to backpatch. 1313 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() { 1314 // Write a placeholder value in for the offset of the real VST, 1315 // which is written after the function blocks so that it can include 1316 // the offset of each function. The placeholder offset will be 1317 // updated when the real VST is written. 1318 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1319 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET)); 1320 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to 1321 // hold the real VST offset. Must use fixed instead of VBR as we don't 1322 // know how many VBR chunks to reserve ahead of time. 1323 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1324 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1325 1326 // Emit the placeholder 1327 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0}; 1328 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals); 1329 1330 // Compute and save the bit offset to the placeholder, which will be 1331 // patched when the real VST is written. We can simply subtract the 32-bit 1332 // fixed size from the current bit number to get the location to backpatch. 1333 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32; 1334 } 1335 1336 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 }; 1337 1338 /// Determine the encoding to use for the given string name and length. 1339 static StringEncoding getStringEncoding(StringRef Str) { 1340 bool isChar6 = true; 1341 for (char C : Str) { 1342 if (isChar6) 1343 isChar6 = BitCodeAbbrevOp::isChar6(C); 1344 if ((unsigned char)C & 128) 1345 // don't bother scanning the rest. 1346 return SE_Fixed8; 1347 } 1348 if (isChar6) 1349 return SE_Char6; 1350 return SE_Fixed7; 1351 } 1352 1353 static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned), 1354 "Sanitizer Metadata is too large for naive serialization."); 1355 static unsigned 1356 serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta) { 1357 return Meta.NoAddress | (Meta.NoHWAddress << 1) | 1358 (Meta.Memtag << 2) | (Meta.IsDynInit << 3); 1359 } 1360 1361 /// Emit top-level description of module, including target triple, inline asm, 1362 /// descriptors for global variables, and function prototype info. 1363 /// Returns the bit offset to backpatch with the location of the real VST. 1364 void ModuleBitcodeWriter::writeModuleInfo() { 1365 // Emit various pieces of data attached to a module. 1366 if (!M.getTargetTriple().empty()) 1367 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(), 1368 0 /*TODO*/); 1369 const std::string &DL = M.getDataLayoutStr(); 1370 if (!DL.empty()) 1371 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/); 1372 if (!M.getModuleInlineAsm().empty()) 1373 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(), 1374 0 /*TODO*/); 1375 1376 // Emit information about sections and GC, computing how many there are. Also 1377 // compute the maximum alignment value. 1378 std::map<std::string, unsigned> SectionMap; 1379 std::map<std::string, unsigned> GCMap; 1380 MaybeAlign MaxAlignment; 1381 unsigned MaxGlobalType = 0; 1382 const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) { 1383 if (A) 1384 MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A); 1385 }; 1386 for (const GlobalVariable &GV : M.globals()) { 1387 UpdateMaxAlignment(GV.getAlign()); 1388 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType())); 1389 if (GV.hasSection()) { 1390 // Give section names unique ID's. 1391 unsigned &Entry = SectionMap[std::string(GV.getSection())]; 1392 if (!Entry) { 1393 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(), 1394 0 /*TODO*/); 1395 Entry = SectionMap.size(); 1396 } 1397 } 1398 } 1399 for (const Function &F : M) { 1400 UpdateMaxAlignment(F.getAlign()); 1401 if (F.hasSection()) { 1402 // Give section names unique ID's. 1403 unsigned &Entry = SectionMap[std::string(F.getSection())]; 1404 if (!Entry) { 1405 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(), 1406 0 /*TODO*/); 1407 Entry = SectionMap.size(); 1408 } 1409 } 1410 if (F.hasGC()) { 1411 // Same for GC names. 1412 unsigned &Entry = GCMap[F.getGC()]; 1413 if (!Entry) { 1414 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(), 1415 0 /*TODO*/); 1416 Entry = GCMap.size(); 1417 } 1418 } 1419 } 1420 1421 // Emit abbrev for globals, now that we know # sections and max alignment. 1422 unsigned SimpleGVarAbbrev = 0; 1423 if (!M.global_empty()) { 1424 // Add an abbrev for common globals with no visibility or thread localness. 1425 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1426 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 1427 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1428 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1429 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1430 Log2_32_Ceil(MaxGlobalType+1))); 1431 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2 1432 //| explicitType << 1 1433 //| constant 1434 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 1435 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage. 1436 if (!MaxAlignment) // Alignment. 1437 Abbv->Add(BitCodeAbbrevOp(0)); 1438 else { 1439 unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment); 1440 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1441 Log2_32_Ceil(MaxEncAlignment+1))); 1442 } 1443 if (SectionMap.empty()) // Section. 1444 Abbv->Add(BitCodeAbbrevOp(0)); 1445 else 1446 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1447 Log2_32_Ceil(SectionMap.size()+1))); 1448 // Don't bother emitting vis + thread local. 1449 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1450 } 1451 1452 SmallVector<unsigned, 64> Vals; 1453 // Emit the module's source file name. 1454 { 1455 StringEncoding Bits = getStringEncoding(M.getSourceFileName()); 1456 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8); 1457 if (Bits == SE_Char6) 1458 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6); 1459 else if (Bits == SE_Fixed7) 1460 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7); 1461 1462 // MODULE_CODE_SOURCE_FILENAME: [namechar x N] 1463 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1464 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME)); 1465 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1466 Abbv->Add(AbbrevOpToUse); 1467 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1468 1469 for (const auto P : M.getSourceFileName()) 1470 Vals.push_back((unsigned char)P); 1471 1472 // Emit the finished record. 1473 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev); 1474 Vals.clear(); 1475 } 1476 1477 // Emit the global variable information. 1478 for (const GlobalVariable &GV : M.globals()) { 1479 unsigned AbbrevToUse = 0; 1480 1481 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid, 1482 // linkage, alignment, section, visibility, threadlocal, 1483 // unnamed_addr, externally_initialized, dllstorageclass, 1484 // comdat, attributes, DSO_Local, GlobalSanitizer, code_model] 1485 Vals.push_back(addToStrtab(GV.getName())); 1486 Vals.push_back(GV.getName().size()); 1487 Vals.push_back(VE.getTypeID(GV.getValueType())); 1488 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant()); 1489 Vals.push_back(GV.isDeclaration() ? 0 : 1490 (VE.getValueID(GV.getInitializer()) + 1)); 1491 Vals.push_back(getEncodedLinkage(GV)); 1492 Vals.push_back(getEncodedAlign(GV.getAlign())); 1493 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())] 1494 : 0); 1495 if (GV.isThreadLocal() || 1496 GV.getVisibility() != GlobalValue::DefaultVisibility || 1497 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None || 1498 GV.isExternallyInitialized() || 1499 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass || 1500 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() || 1501 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) { 1502 Vals.push_back(getEncodedVisibility(GV)); 1503 Vals.push_back(getEncodedThreadLocalMode(GV)); 1504 Vals.push_back(getEncodedUnnamedAddr(GV)); 1505 Vals.push_back(GV.isExternallyInitialized()); 1506 Vals.push_back(getEncodedDLLStorageClass(GV)); 1507 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0); 1508 1509 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex); 1510 Vals.push_back(VE.getAttributeListID(AL)); 1511 1512 Vals.push_back(GV.isDSOLocal()); 1513 Vals.push_back(addToStrtab(GV.getPartition())); 1514 Vals.push_back(GV.getPartition().size()); 1515 1516 Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata( 1517 GV.getSanitizerMetadata()) 1518 : 0)); 1519 Vals.push_back(GV.getCodeModelRaw()); 1520 } else { 1521 AbbrevToUse = SimpleGVarAbbrev; 1522 } 1523 1524 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 1525 Vals.clear(); 1526 } 1527 1528 // Emit the function proto information. 1529 for (const Function &F : M) { 1530 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto, 1531 // linkage, paramattrs, alignment, section, visibility, gc, 1532 // unnamed_addr, prologuedata, dllstorageclass, comdat, 1533 // prefixdata, personalityfn, DSO_Local, addrspace] 1534 Vals.push_back(addToStrtab(F.getName())); 1535 Vals.push_back(F.getName().size()); 1536 Vals.push_back(VE.getTypeID(F.getFunctionType())); 1537 Vals.push_back(F.getCallingConv()); 1538 Vals.push_back(F.isDeclaration()); 1539 Vals.push_back(getEncodedLinkage(F)); 1540 Vals.push_back(VE.getAttributeListID(F.getAttributes())); 1541 Vals.push_back(getEncodedAlign(F.getAlign())); 1542 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())] 1543 : 0); 1544 Vals.push_back(getEncodedVisibility(F)); 1545 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0); 1546 Vals.push_back(getEncodedUnnamedAddr(F)); 1547 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1) 1548 : 0); 1549 Vals.push_back(getEncodedDLLStorageClass(F)); 1550 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0); 1551 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1) 1552 : 0); 1553 Vals.push_back( 1554 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0); 1555 1556 Vals.push_back(F.isDSOLocal()); 1557 Vals.push_back(F.getAddressSpace()); 1558 Vals.push_back(addToStrtab(F.getPartition())); 1559 Vals.push_back(F.getPartition().size()); 1560 1561 unsigned AbbrevToUse = 0; 1562 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 1563 Vals.clear(); 1564 } 1565 1566 // Emit the alias information. 1567 for (const GlobalAlias &A : M.aliases()) { 1568 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage, 1569 // visibility, dllstorageclass, threadlocal, unnamed_addr, 1570 // DSO_Local] 1571 Vals.push_back(addToStrtab(A.getName())); 1572 Vals.push_back(A.getName().size()); 1573 Vals.push_back(VE.getTypeID(A.getValueType())); 1574 Vals.push_back(A.getType()->getAddressSpace()); 1575 Vals.push_back(VE.getValueID(A.getAliasee())); 1576 Vals.push_back(getEncodedLinkage(A)); 1577 Vals.push_back(getEncodedVisibility(A)); 1578 Vals.push_back(getEncodedDLLStorageClass(A)); 1579 Vals.push_back(getEncodedThreadLocalMode(A)); 1580 Vals.push_back(getEncodedUnnamedAddr(A)); 1581 Vals.push_back(A.isDSOLocal()); 1582 Vals.push_back(addToStrtab(A.getPartition())); 1583 Vals.push_back(A.getPartition().size()); 1584 1585 unsigned AbbrevToUse = 0; 1586 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse); 1587 Vals.clear(); 1588 } 1589 1590 // Emit the ifunc information. 1591 for (const GlobalIFunc &I : M.ifuncs()) { 1592 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver 1593 // val#, linkage, visibility, DSO_Local] 1594 Vals.push_back(addToStrtab(I.getName())); 1595 Vals.push_back(I.getName().size()); 1596 Vals.push_back(VE.getTypeID(I.getValueType())); 1597 Vals.push_back(I.getType()->getAddressSpace()); 1598 Vals.push_back(VE.getValueID(I.getResolver())); 1599 Vals.push_back(getEncodedLinkage(I)); 1600 Vals.push_back(getEncodedVisibility(I)); 1601 Vals.push_back(I.isDSOLocal()); 1602 Vals.push_back(addToStrtab(I.getPartition())); 1603 Vals.push_back(I.getPartition().size()); 1604 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals); 1605 Vals.clear(); 1606 } 1607 1608 writeValueSymbolTableForwardDecl(); 1609 } 1610 1611 static uint64_t getOptimizationFlags(const Value *V) { 1612 uint64_t Flags = 0; 1613 1614 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) { 1615 if (OBO->hasNoSignedWrap()) 1616 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP; 1617 if (OBO->hasNoUnsignedWrap()) 1618 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP; 1619 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) { 1620 if (PEO->isExact()) 1621 Flags |= 1 << bitc::PEO_EXACT; 1622 } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) { 1623 if (PDI->isDisjoint()) 1624 Flags |= 1 << bitc::PDI_DISJOINT; 1625 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) { 1626 if (FPMO->hasAllowReassoc()) 1627 Flags |= bitc::AllowReassoc; 1628 if (FPMO->hasNoNaNs()) 1629 Flags |= bitc::NoNaNs; 1630 if (FPMO->hasNoInfs()) 1631 Flags |= bitc::NoInfs; 1632 if (FPMO->hasNoSignedZeros()) 1633 Flags |= bitc::NoSignedZeros; 1634 if (FPMO->hasAllowReciprocal()) 1635 Flags |= bitc::AllowReciprocal; 1636 if (FPMO->hasAllowContract()) 1637 Flags |= bitc::AllowContract; 1638 if (FPMO->hasApproxFunc()) 1639 Flags |= bitc::ApproxFunc; 1640 } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) { 1641 if (NNI->hasNonNeg()) 1642 Flags |= 1 << bitc::PNNI_NON_NEG; 1643 } 1644 1645 return Flags; 1646 } 1647 1648 void ModuleBitcodeWriter::writeValueAsMetadata( 1649 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) { 1650 // Mimic an MDNode with a value as one operand. 1651 Value *V = MD->getValue(); 1652 Record.push_back(VE.getTypeID(V->getType())); 1653 Record.push_back(VE.getValueID(V)); 1654 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0); 1655 Record.clear(); 1656 } 1657 1658 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N, 1659 SmallVectorImpl<uint64_t> &Record, 1660 unsigned Abbrev) { 1661 for (const MDOperand &MDO : N->operands()) { 1662 Metadata *MD = MDO; 1663 assert(!(MD && isa<LocalAsMetadata>(MD)) && 1664 "Unexpected function-local metadata"); 1665 Record.push_back(VE.getMetadataOrNullID(MD)); 1666 } 1667 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE 1668 : bitc::METADATA_NODE, 1669 Record, Abbrev); 1670 Record.clear(); 1671 } 1672 1673 unsigned ModuleBitcodeWriter::createDILocationAbbrev() { 1674 // Assume the column is usually under 128, and always output the inlined-at 1675 // location (it's never more expensive than building an array size 1). 1676 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1677 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION)); 1678 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1679 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1680 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1681 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1682 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1683 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1684 return Stream.EmitAbbrev(std::move(Abbv)); 1685 } 1686 1687 void ModuleBitcodeWriter::writeDILocation(const DILocation *N, 1688 SmallVectorImpl<uint64_t> &Record, 1689 unsigned &Abbrev) { 1690 if (!Abbrev) 1691 Abbrev = createDILocationAbbrev(); 1692 1693 Record.push_back(N->isDistinct()); 1694 Record.push_back(N->getLine()); 1695 Record.push_back(N->getColumn()); 1696 Record.push_back(VE.getMetadataID(N->getScope())); 1697 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt())); 1698 Record.push_back(N->isImplicitCode()); 1699 1700 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev); 1701 Record.clear(); 1702 } 1703 1704 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() { 1705 // Assume the column is usually under 128, and always output the inlined-at 1706 // location (it's never more expensive than building an array size 1). 1707 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1708 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG)); 1709 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1710 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1711 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1712 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1713 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1714 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1715 return Stream.EmitAbbrev(std::move(Abbv)); 1716 } 1717 1718 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N, 1719 SmallVectorImpl<uint64_t> &Record, 1720 unsigned &Abbrev) { 1721 if (!Abbrev) 1722 Abbrev = createGenericDINodeAbbrev(); 1723 1724 Record.push_back(N->isDistinct()); 1725 Record.push_back(N->getTag()); 1726 Record.push_back(0); // Per-tag version field; unused for now. 1727 1728 for (auto &I : N->operands()) 1729 Record.push_back(VE.getMetadataOrNullID(I)); 1730 1731 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev); 1732 Record.clear(); 1733 } 1734 1735 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N, 1736 SmallVectorImpl<uint64_t> &Record, 1737 unsigned Abbrev) { 1738 const uint64_t Version = 2 << 1; 1739 Record.push_back((uint64_t)N->isDistinct() | Version); 1740 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode())); 1741 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound())); 1742 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound())); 1743 Record.push_back(VE.getMetadataOrNullID(N->getRawStride())); 1744 1745 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev); 1746 Record.clear(); 1747 } 1748 1749 void ModuleBitcodeWriter::writeDIGenericSubrange( 1750 const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record, 1751 unsigned Abbrev) { 1752 Record.push_back((uint64_t)N->isDistinct()); 1753 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode())); 1754 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound())); 1755 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound())); 1756 Record.push_back(VE.getMetadataOrNullID(N->getRawStride())); 1757 1758 Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev); 1759 Record.clear(); 1760 } 1761 1762 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N, 1763 SmallVectorImpl<uint64_t> &Record, 1764 unsigned Abbrev) { 1765 const uint64_t IsBigInt = 1 << 2; 1766 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct()); 1767 Record.push_back(N->getValue().getBitWidth()); 1768 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1769 emitWideAPInt(Record, N->getValue()); 1770 1771 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev); 1772 Record.clear(); 1773 } 1774 1775 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N, 1776 SmallVectorImpl<uint64_t> &Record, 1777 unsigned Abbrev) { 1778 Record.push_back(N->isDistinct()); 1779 Record.push_back(N->getTag()); 1780 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1781 Record.push_back(N->getSizeInBits()); 1782 Record.push_back(N->getAlignInBits()); 1783 Record.push_back(N->getEncoding()); 1784 Record.push_back(N->getFlags()); 1785 1786 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev); 1787 Record.clear(); 1788 } 1789 1790 void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N, 1791 SmallVectorImpl<uint64_t> &Record, 1792 unsigned Abbrev) { 1793 Record.push_back(N->isDistinct()); 1794 Record.push_back(N->getTag()); 1795 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1796 Record.push_back(VE.getMetadataOrNullID(N->getStringLength())); 1797 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp())); 1798 Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp())); 1799 Record.push_back(N->getSizeInBits()); 1800 Record.push_back(N->getAlignInBits()); 1801 Record.push_back(N->getEncoding()); 1802 1803 Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev); 1804 Record.clear(); 1805 } 1806 1807 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N, 1808 SmallVectorImpl<uint64_t> &Record, 1809 unsigned Abbrev) { 1810 Record.push_back(N->isDistinct()); 1811 Record.push_back(N->getTag()); 1812 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1813 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1814 Record.push_back(N->getLine()); 1815 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1816 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1817 Record.push_back(N->getSizeInBits()); 1818 Record.push_back(N->getAlignInBits()); 1819 Record.push_back(N->getOffsetInBits()); 1820 Record.push_back(N->getFlags()); 1821 Record.push_back(VE.getMetadataOrNullID(N->getExtraData())); 1822 1823 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means 1824 // that there is no DWARF address space associated with DIDerivedType. 1825 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace()) 1826 Record.push_back(*DWARFAddressSpace + 1); 1827 else 1828 Record.push_back(0); 1829 1830 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get())); 1831 1832 if (auto PtrAuthData = N->getPtrAuthData()) 1833 Record.push_back(PtrAuthData->RawData); 1834 else 1835 Record.push_back(0); 1836 1837 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev); 1838 Record.clear(); 1839 } 1840 1841 void ModuleBitcodeWriter::writeDICompositeType( 1842 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record, 1843 unsigned Abbrev) { 1844 const unsigned IsNotUsedInOldTypeRef = 0x2; 1845 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct()); 1846 Record.push_back(N->getTag()); 1847 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1848 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1849 Record.push_back(N->getLine()); 1850 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1851 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1852 Record.push_back(N->getSizeInBits()); 1853 Record.push_back(N->getAlignInBits()); 1854 Record.push_back(N->getOffsetInBits()); 1855 Record.push_back(N->getFlags()); 1856 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 1857 Record.push_back(N->getRuntimeLang()); 1858 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder())); 1859 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1860 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier())); 1861 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator())); 1862 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation())); 1863 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated())); 1864 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated())); 1865 Record.push_back(VE.getMetadataOrNullID(N->getRawRank())); 1866 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get())); 1867 1868 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev); 1869 Record.clear(); 1870 } 1871 1872 void ModuleBitcodeWriter::writeDISubroutineType( 1873 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record, 1874 unsigned Abbrev) { 1875 const unsigned HasNoOldTypeRefs = 0x2; 1876 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct()); 1877 Record.push_back(N->getFlags()); 1878 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get())); 1879 Record.push_back(N->getCC()); 1880 1881 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev); 1882 Record.clear(); 1883 } 1884 1885 void ModuleBitcodeWriter::writeDIFile(const DIFile *N, 1886 SmallVectorImpl<uint64_t> &Record, 1887 unsigned Abbrev) { 1888 Record.push_back(N->isDistinct()); 1889 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename())); 1890 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory())); 1891 if (N->getRawChecksum()) { 1892 Record.push_back(N->getRawChecksum()->Kind); 1893 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value)); 1894 } else { 1895 // Maintain backwards compatibility with the old internal representation of 1896 // CSK_None in ChecksumKind by writing nulls here when Checksum is None. 1897 Record.push_back(0); 1898 Record.push_back(VE.getMetadataOrNullID(nullptr)); 1899 } 1900 auto Source = N->getRawSource(); 1901 if (Source) 1902 Record.push_back(VE.getMetadataOrNullID(Source)); 1903 1904 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev); 1905 Record.clear(); 1906 } 1907 1908 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N, 1909 SmallVectorImpl<uint64_t> &Record, 1910 unsigned Abbrev) { 1911 assert(N->isDistinct() && "Expected distinct compile units"); 1912 Record.push_back(/* IsDistinct */ true); 1913 Record.push_back(N->getSourceLanguage()); 1914 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1915 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer())); 1916 Record.push_back(N->isOptimized()); 1917 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags())); 1918 Record.push_back(N->getRuntimeVersion()); 1919 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename())); 1920 Record.push_back(N->getEmissionKind()); 1921 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get())); 1922 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get())); 1923 Record.push_back(/* subprograms */ 0); 1924 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get())); 1925 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get())); 1926 Record.push_back(N->getDWOId()); 1927 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get())); 1928 Record.push_back(N->getSplitDebugInlining()); 1929 Record.push_back(N->getDebugInfoForProfiling()); 1930 Record.push_back((unsigned)N->getNameTableKind()); 1931 Record.push_back(N->getRangesBaseAddress()); 1932 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot())); 1933 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK())); 1934 1935 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev); 1936 Record.clear(); 1937 } 1938 1939 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N, 1940 SmallVectorImpl<uint64_t> &Record, 1941 unsigned Abbrev) { 1942 const uint64_t HasUnitFlag = 1 << 1; 1943 const uint64_t HasSPFlagsFlag = 1 << 2; 1944 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag); 1945 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1946 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1947 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1948 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1949 Record.push_back(N->getLine()); 1950 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1951 Record.push_back(N->getScopeLine()); 1952 Record.push_back(VE.getMetadataOrNullID(N->getContainingType())); 1953 Record.push_back(N->getSPFlags()); 1954 Record.push_back(N->getVirtualIndex()); 1955 Record.push_back(N->getFlags()); 1956 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit())); 1957 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1958 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration())); 1959 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get())); 1960 Record.push_back(N->getThisAdjustment()); 1961 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get())); 1962 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get())); 1963 Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName())); 1964 1965 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev); 1966 Record.clear(); 1967 } 1968 1969 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N, 1970 SmallVectorImpl<uint64_t> &Record, 1971 unsigned Abbrev) { 1972 Record.push_back(N->isDistinct()); 1973 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1974 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1975 Record.push_back(N->getLine()); 1976 Record.push_back(N->getColumn()); 1977 1978 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev); 1979 Record.clear(); 1980 } 1981 1982 void ModuleBitcodeWriter::writeDILexicalBlockFile( 1983 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record, 1984 unsigned Abbrev) { 1985 Record.push_back(N->isDistinct()); 1986 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1987 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1988 Record.push_back(N->getDiscriminator()); 1989 1990 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev); 1991 Record.clear(); 1992 } 1993 1994 void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N, 1995 SmallVectorImpl<uint64_t> &Record, 1996 unsigned Abbrev) { 1997 Record.push_back(N->isDistinct()); 1998 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1999 Record.push_back(VE.getMetadataOrNullID(N->getDecl())); 2000 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2001 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2002 Record.push_back(N->getLineNo()); 2003 2004 Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev); 2005 Record.clear(); 2006 } 2007 2008 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N, 2009 SmallVectorImpl<uint64_t> &Record, 2010 unsigned Abbrev) { 2011 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1); 2012 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 2013 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2014 2015 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev); 2016 Record.clear(); 2017 } 2018 2019 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N, 2020 SmallVectorImpl<uint64_t> &Record, 2021 unsigned Abbrev) { 2022 Record.push_back(N->isDistinct()); 2023 Record.push_back(N->getMacinfoType()); 2024 Record.push_back(N->getLine()); 2025 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2026 Record.push_back(VE.getMetadataOrNullID(N->getRawValue())); 2027 2028 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev); 2029 Record.clear(); 2030 } 2031 2032 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N, 2033 SmallVectorImpl<uint64_t> &Record, 2034 unsigned Abbrev) { 2035 Record.push_back(N->isDistinct()); 2036 Record.push_back(N->getMacinfoType()); 2037 Record.push_back(N->getLine()); 2038 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2039 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 2040 2041 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev); 2042 Record.clear(); 2043 } 2044 2045 void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N, 2046 SmallVectorImpl<uint64_t> &Record) { 2047 Record.reserve(N->getArgs().size()); 2048 for (ValueAsMetadata *MD : N->getArgs()) 2049 Record.push_back(VE.getMetadataID(MD)); 2050 2051 Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record); 2052 Record.clear(); 2053 } 2054 2055 void ModuleBitcodeWriter::writeDIModule(const DIModule *N, 2056 SmallVectorImpl<uint64_t> &Record, 2057 unsigned Abbrev) { 2058 Record.push_back(N->isDistinct()); 2059 for (auto &I : N->operands()) 2060 Record.push_back(VE.getMetadataOrNullID(I)); 2061 Record.push_back(N->getLineNo()); 2062 Record.push_back(N->getIsDecl()); 2063 2064 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev); 2065 Record.clear(); 2066 } 2067 2068 void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N, 2069 SmallVectorImpl<uint64_t> &Record, 2070 unsigned Abbrev) { 2071 // There are no arguments for this metadata type. 2072 Record.push_back(N->isDistinct()); 2073 Stream.EmitRecord(bitc::METADATA_ASSIGN_ID, Record, Abbrev); 2074 Record.clear(); 2075 } 2076 2077 void ModuleBitcodeWriter::writeDITemplateTypeParameter( 2078 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record, 2079 unsigned Abbrev) { 2080 Record.push_back(N->isDistinct()); 2081 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2082 Record.push_back(VE.getMetadataOrNullID(N->getType())); 2083 Record.push_back(N->isDefault()); 2084 2085 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev); 2086 Record.clear(); 2087 } 2088 2089 void ModuleBitcodeWriter::writeDITemplateValueParameter( 2090 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record, 2091 unsigned Abbrev) { 2092 Record.push_back(N->isDistinct()); 2093 Record.push_back(N->getTag()); 2094 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2095 Record.push_back(VE.getMetadataOrNullID(N->getType())); 2096 Record.push_back(N->isDefault()); 2097 Record.push_back(VE.getMetadataOrNullID(N->getValue())); 2098 2099 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev); 2100 Record.clear(); 2101 } 2102 2103 void ModuleBitcodeWriter::writeDIGlobalVariable( 2104 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record, 2105 unsigned Abbrev) { 2106 const uint64_t Version = 2 << 1; 2107 Record.push_back((uint64_t)N->isDistinct() | Version); 2108 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 2109 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2110 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 2111 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2112 Record.push_back(N->getLine()); 2113 Record.push_back(VE.getMetadataOrNullID(N->getType())); 2114 Record.push_back(N->isLocalToUnit()); 2115 Record.push_back(N->isDefinition()); 2116 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration())); 2117 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams())); 2118 Record.push_back(N->getAlignInBits()); 2119 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get())); 2120 2121 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev); 2122 Record.clear(); 2123 } 2124 2125 void ModuleBitcodeWriter::writeDILocalVariable( 2126 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record, 2127 unsigned Abbrev) { 2128 // In order to support all possible bitcode formats in BitcodeReader we need 2129 // to distinguish the following cases: 2130 // 1) Record has no artificial tag (Record[1]), 2131 // has no obsolete inlinedAt field (Record[9]). 2132 // In this case Record size will be 8, HasAlignment flag is false. 2133 // 2) Record has artificial tag (Record[1]), 2134 // has no obsolete inlignedAt field (Record[9]). 2135 // In this case Record size will be 9, HasAlignment flag is false. 2136 // 3) Record has both artificial tag (Record[1]) and 2137 // obsolete inlignedAt field (Record[9]). 2138 // In this case Record size will be 10, HasAlignment flag is false. 2139 // 4) Record has neither artificial tag, nor inlignedAt field, but 2140 // HasAlignment flag is true and Record[8] contains alignment value. 2141 const uint64_t HasAlignmentFlag = 1 << 1; 2142 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag); 2143 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 2144 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2145 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2146 Record.push_back(N->getLine()); 2147 Record.push_back(VE.getMetadataOrNullID(N->getType())); 2148 Record.push_back(N->getArg()); 2149 Record.push_back(N->getFlags()); 2150 Record.push_back(N->getAlignInBits()); 2151 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get())); 2152 2153 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev); 2154 Record.clear(); 2155 } 2156 2157 void ModuleBitcodeWriter::writeDILabel( 2158 const DILabel *N, SmallVectorImpl<uint64_t> &Record, 2159 unsigned Abbrev) { 2160 Record.push_back((uint64_t)N->isDistinct()); 2161 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 2162 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2163 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2164 Record.push_back(N->getLine()); 2165 2166 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev); 2167 Record.clear(); 2168 } 2169 2170 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N, 2171 SmallVectorImpl<uint64_t> &Record, 2172 unsigned Abbrev) { 2173 Record.reserve(N->getElements().size() + 1); 2174 const uint64_t Version = 3 << 1; 2175 Record.push_back((uint64_t)N->isDistinct() | Version); 2176 Record.append(N->elements_begin(), N->elements_end()); 2177 2178 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev); 2179 Record.clear(); 2180 } 2181 2182 void ModuleBitcodeWriter::writeDIGlobalVariableExpression( 2183 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record, 2184 unsigned Abbrev) { 2185 Record.push_back(N->isDistinct()); 2186 Record.push_back(VE.getMetadataOrNullID(N->getVariable())); 2187 Record.push_back(VE.getMetadataOrNullID(N->getExpression())); 2188 2189 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev); 2190 Record.clear(); 2191 } 2192 2193 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N, 2194 SmallVectorImpl<uint64_t> &Record, 2195 unsigned Abbrev) { 2196 Record.push_back(N->isDistinct()); 2197 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2198 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 2199 Record.push_back(N->getLine()); 2200 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName())); 2201 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName())); 2202 Record.push_back(N->getAttributes()); 2203 Record.push_back(VE.getMetadataOrNullID(N->getType())); 2204 2205 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev); 2206 Record.clear(); 2207 } 2208 2209 void ModuleBitcodeWriter::writeDIImportedEntity( 2210 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record, 2211 unsigned Abbrev) { 2212 Record.push_back(N->isDistinct()); 2213 Record.push_back(N->getTag()); 2214 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 2215 Record.push_back(VE.getMetadataOrNullID(N->getEntity())); 2216 Record.push_back(N->getLine()); 2217 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2218 Record.push_back(VE.getMetadataOrNullID(N->getRawFile())); 2219 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 2220 2221 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev); 2222 Record.clear(); 2223 } 2224 2225 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() { 2226 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2227 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME)); 2228 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2229 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2230 return Stream.EmitAbbrev(std::move(Abbv)); 2231 } 2232 2233 void ModuleBitcodeWriter::writeNamedMetadata( 2234 SmallVectorImpl<uint64_t> &Record) { 2235 if (M.named_metadata_empty()) 2236 return; 2237 2238 unsigned Abbrev = createNamedMetadataAbbrev(); 2239 for (const NamedMDNode &NMD : M.named_metadata()) { 2240 // Write name. 2241 StringRef Str = NMD.getName(); 2242 Record.append(Str.bytes_begin(), Str.bytes_end()); 2243 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev); 2244 Record.clear(); 2245 2246 // Write named metadata operands. 2247 for (const MDNode *N : NMD.operands()) 2248 Record.push_back(VE.getMetadataID(N)); 2249 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0); 2250 Record.clear(); 2251 } 2252 } 2253 2254 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() { 2255 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2256 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS)); 2257 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings 2258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars 2259 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2260 return Stream.EmitAbbrev(std::move(Abbv)); 2261 } 2262 2263 /// Write out a record for MDString. 2264 /// 2265 /// All the metadata strings in a metadata block are emitted in a single 2266 /// record. The sizes and strings themselves are shoved into a blob. 2267 void ModuleBitcodeWriter::writeMetadataStrings( 2268 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) { 2269 if (Strings.empty()) 2270 return; 2271 2272 // Start the record with the number of strings. 2273 Record.push_back(bitc::METADATA_STRINGS); 2274 Record.push_back(Strings.size()); 2275 2276 // Emit the sizes of the strings in the blob. 2277 SmallString<256> Blob; 2278 { 2279 BitstreamWriter W(Blob); 2280 for (const Metadata *MD : Strings) 2281 W.EmitVBR(cast<MDString>(MD)->getLength(), 6); 2282 W.FlushToWord(); 2283 } 2284 2285 // Add the offset to the strings to the record. 2286 Record.push_back(Blob.size()); 2287 2288 // Add the strings to the blob. 2289 for (const Metadata *MD : Strings) 2290 Blob.append(cast<MDString>(MD)->getString()); 2291 2292 // Emit the final record. 2293 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob); 2294 Record.clear(); 2295 } 2296 2297 // Generates an enum to use as an index in the Abbrev array of Metadata record. 2298 enum MetadataAbbrev : unsigned { 2299 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID, 2300 #include "llvm/IR/Metadata.def" 2301 LastPlusOne 2302 }; 2303 2304 void ModuleBitcodeWriter::writeMetadataRecords( 2305 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record, 2306 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) { 2307 if (MDs.empty()) 2308 return; 2309 2310 // Initialize MDNode abbreviations. 2311 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0; 2312 #include "llvm/IR/Metadata.def" 2313 2314 for (const Metadata *MD : MDs) { 2315 if (IndexPos) 2316 IndexPos->push_back(Stream.GetCurrentBitNo()); 2317 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 2318 assert(N->isResolved() && "Expected forward references to be resolved"); 2319 2320 switch (N->getMetadataID()) { 2321 default: 2322 llvm_unreachable("Invalid MDNode subclass"); 2323 #define HANDLE_MDNODE_LEAF(CLASS) \ 2324 case Metadata::CLASS##Kind: \ 2325 if (MDAbbrevs) \ 2326 write##CLASS(cast<CLASS>(N), Record, \ 2327 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \ 2328 else \ 2329 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \ 2330 continue; 2331 #include "llvm/IR/Metadata.def" 2332 } 2333 } 2334 if (auto *AL = dyn_cast<DIArgList>(MD)) { 2335 writeDIArgList(AL, Record); 2336 continue; 2337 } 2338 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record); 2339 } 2340 } 2341 2342 void ModuleBitcodeWriter::writeModuleMetadata() { 2343 if (!VE.hasMDs() && M.named_metadata_empty()) 2344 return; 2345 2346 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4); 2347 SmallVector<uint64_t, 64> Record; 2348 2349 // Emit all abbrevs upfront, so that the reader can jump in the middle of the 2350 // block and load any metadata. 2351 std::vector<unsigned> MDAbbrevs; 2352 2353 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne); 2354 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev(); 2355 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] = 2356 createGenericDINodeAbbrev(); 2357 2358 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2359 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET)); 2360 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2361 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2362 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 2363 2364 Abbv = std::make_shared<BitCodeAbbrev>(); 2365 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX)); 2366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 2368 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 2369 2370 // Emit MDStrings together upfront. 2371 writeMetadataStrings(VE.getMDStrings(), Record); 2372 2373 // We only emit an index for the metadata record if we have more than a given 2374 // (naive) threshold of metadatas, otherwise it is not worth it. 2375 if (VE.getNonMDStrings().size() > IndexThreshold) { 2376 // Write a placeholder value in for the offset of the metadata index, 2377 // which is written after the records, so that it can include 2378 // the offset of each entry. The placeholder offset will be 2379 // updated after all records are emitted. 2380 uint64_t Vals[] = {0, 0}; 2381 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev); 2382 } 2383 2384 // Compute and save the bit offset to the current position, which will be 2385 // patched when we emit the index later. We can simply subtract the 64-bit 2386 // fixed size from the current bit number to get the location to backpatch. 2387 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo(); 2388 2389 // This index will contain the bitpos for each individual record. 2390 std::vector<uint64_t> IndexPos; 2391 IndexPos.reserve(VE.getNonMDStrings().size()); 2392 2393 // Write all the records 2394 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos); 2395 2396 if (VE.getNonMDStrings().size() > IndexThreshold) { 2397 // Now that we have emitted all the records we will emit the index. But 2398 // first 2399 // backpatch the forward reference so that the reader can skip the records 2400 // efficiently. 2401 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64, 2402 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos); 2403 2404 // Delta encode the index. 2405 uint64_t PreviousValue = IndexOffsetRecordBitPos; 2406 for (auto &Elt : IndexPos) { 2407 auto EltDelta = Elt - PreviousValue; 2408 PreviousValue = Elt; 2409 Elt = EltDelta; 2410 } 2411 // Emit the index record. 2412 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev); 2413 IndexPos.clear(); 2414 } 2415 2416 // Write the named metadata now. 2417 writeNamedMetadata(Record); 2418 2419 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) { 2420 SmallVector<uint64_t, 4> Record; 2421 Record.push_back(VE.getValueID(&GO)); 2422 pushGlobalMetadataAttachment(Record, GO); 2423 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record); 2424 }; 2425 for (const Function &F : M) 2426 if (F.isDeclaration() && F.hasMetadata()) 2427 AddDeclAttachedMetadata(F); 2428 // FIXME: Only store metadata for declarations here, and move data for global 2429 // variable definitions to a separate block (PR28134). 2430 for (const GlobalVariable &GV : M.globals()) 2431 if (GV.hasMetadata()) 2432 AddDeclAttachedMetadata(GV); 2433 2434 Stream.ExitBlock(); 2435 } 2436 2437 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) { 2438 if (!VE.hasMDs()) 2439 return; 2440 2441 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 2442 SmallVector<uint64_t, 64> Record; 2443 writeMetadataStrings(VE.getMDStrings(), Record); 2444 writeMetadataRecords(VE.getNonMDStrings(), Record); 2445 Stream.ExitBlock(); 2446 } 2447 2448 void ModuleBitcodeWriter::pushGlobalMetadataAttachment( 2449 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) { 2450 // [n x [id, mdnode]] 2451 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2452 GO.getAllMetadata(MDs); 2453 for (const auto &I : MDs) { 2454 Record.push_back(I.first); 2455 Record.push_back(VE.getMetadataID(I.second)); 2456 } 2457 } 2458 2459 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) { 2460 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); 2461 2462 SmallVector<uint64_t, 64> Record; 2463 2464 if (F.hasMetadata()) { 2465 pushGlobalMetadataAttachment(Record, F); 2466 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 2467 Record.clear(); 2468 } 2469 2470 // Write metadata attachments 2471 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] 2472 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2473 for (const BasicBlock &BB : F) 2474 for (const Instruction &I : BB) { 2475 MDs.clear(); 2476 I.getAllMetadataOtherThanDebugLoc(MDs); 2477 2478 // If no metadata, ignore instruction. 2479 if (MDs.empty()) continue; 2480 2481 Record.push_back(VE.getInstructionID(&I)); 2482 2483 for (unsigned i = 0, e = MDs.size(); i != e; ++i) { 2484 Record.push_back(MDs[i].first); 2485 Record.push_back(VE.getMetadataID(MDs[i].second)); 2486 } 2487 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 2488 Record.clear(); 2489 } 2490 2491 Stream.ExitBlock(); 2492 } 2493 2494 void ModuleBitcodeWriter::writeModuleMetadataKinds() { 2495 SmallVector<uint64_t, 64> Record; 2496 2497 // Write metadata kinds 2498 // METADATA_KIND - [n x [id, name]] 2499 SmallVector<StringRef, 8> Names; 2500 M.getMDKindNames(Names); 2501 2502 if (Names.empty()) return; 2503 2504 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3); 2505 2506 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) { 2507 Record.push_back(MDKindID); 2508 StringRef KName = Names[MDKindID]; 2509 Record.append(KName.begin(), KName.end()); 2510 2511 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); 2512 Record.clear(); 2513 } 2514 2515 Stream.ExitBlock(); 2516 } 2517 2518 void ModuleBitcodeWriter::writeOperandBundleTags() { 2519 // Write metadata kinds 2520 // 2521 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG 2522 // 2523 // OPERAND_BUNDLE_TAG - [strchr x N] 2524 2525 SmallVector<StringRef, 8> Tags; 2526 M.getOperandBundleTags(Tags); 2527 2528 if (Tags.empty()) 2529 return; 2530 2531 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3); 2532 2533 SmallVector<uint64_t, 64> Record; 2534 2535 for (auto Tag : Tags) { 2536 Record.append(Tag.begin(), Tag.end()); 2537 2538 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0); 2539 Record.clear(); 2540 } 2541 2542 Stream.ExitBlock(); 2543 } 2544 2545 void ModuleBitcodeWriter::writeSyncScopeNames() { 2546 SmallVector<StringRef, 8> SSNs; 2547 M.getContext().getSyncScopeNames(SSNs); 2548 if (SSNs.empty()) 2549 return; 2550 2551 Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2); 2552 2553 SmallVector<uint64_t, 64> Record; 2554 for (auto SSN : SSNs) { 2555 Record.append(SSN.begin(), SSN.end()); 2556 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0); 2557 Record.clear(); 2558 } 2559 2560 Stream.ExitBlock(); 2561 } 2562 2563 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal, 2564 bool isGlobal) { 2565 if (FirstVal == LastVal) return; 2566 2567 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); 2568 2569 unsigned AggregateAbbrev = 0; 2570 unsigned String8Abbrev = 0; 2571 unsigned CString7Abbrev = 0; 2572 unsigned CString6Abbrev = 0; 2573 // If this is a constant pool for the module, emit module-specific abbrevs. 2574 if (isGlobal) { 2575 // Abbrev for CST_CODE_AGGREGATE. 2576 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2577 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE)); 2578 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2579 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1))); 2580 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 2581 2582 // Abbrev for CST_CODE_STRING. 2583 Abbv = std::make_shared<BitCodeAbbrev>(); 2584 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING)); 2585 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2586 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2587 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 2588 // Abbrev for CST_CODE_CSTRING. 2589 Abbv = std::make_shared<BitCodeAbbrev>(); 2590 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 2591 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2592 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 2593 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 2594 // Abbrev for CST_CODE_CSTRING. 2595 Abbv = std::make_shared<BitCodeAbbrev>(); 2596 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 2597 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2598 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2599 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 2600 } 2601 2602 SmallVector<uint64_t, 64> Record; 2603 2604 const ValueEnumerator::ValueList &Vals = VE.getValues(); 2605 Type *LastTy = nullptr; 2606 for (unsigned i = FirstVal; i != LastVal; ++i) { 2607 const Value *V = Vals[i].first; 2608 // If we need to switch types, do so now. 2609 if (V->getType() != LastTy) { 2610 LastTy = V->getType(); 2611 Record.push_back(VE.getTypeID(LastTy)); 2612 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record, 2613 CONSTANTS_SETTYPE_ABBREV); 2614 Record.clear(); 2615 } 2616 2617 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 2618 Record.push_back(VE.getTypeID(IA->getFunctionType())); 2619 Record.push_back( 2620 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 | 2621 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3); 2622 2623 // Add the asm string. 2624 const std::string &AsmStr = IA->getAsmString(); 2625 Record.push_back(AsmStr.size()); 2626 Record.append(AsmStr.begin(), AsmStr.end()); 2627 2628 // Add the constraint string. 2629 const std::string &ConstraintStr = IA->getConstraintString(); 2630 Record.push_back(ConstraintStr.size()); 2631 Record.append(ConstraintStr.begin(), ConstraintStr.end()); 2632 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record); 2633 Record.clear(); 2634 continue; 2635 } 2636 const Constant *C = cast<Constant>(V); 2637 unsigned Code = -1U; 2638 unsigned AbbrevToUse = 0; 2639 if (C->isNullValue()) { 2640 Code = bitc::CST_CODE_NULL; 2641 } else if (isa<PoisonValue>(C)) { 2642 Code = bitc::CST_CODE_POISON; 2643 } else if (isa<UndefValue>(C)) { 2644 Code = bitc::CST_CODE_UNDEF; 2645 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 2646 if (IV->getBitWidth() <= 64) { 2647 uint64_t V = IV->getSExtValue(); 2648 emitSignedInt64(Record, V); 2649 Code = bitc::CST_CODE_INTEGER; 2650 AbbrevToUse = CONSTANTS_INTEGER_ABBREV; 2651 } else { // Wide integers, > 64 bits in size. 2652 emitWideAPInt(Record, IV->getValue()); 2653 Code = bitc::CST_CODE_WIDE_INTEGER; 2654 } 2655 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 2656 Code = bitc::CST_CODE_FLOAT; 2657 Type *Ty = CFP->getType()->getScalarType(); 2658 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || 2659 Ty->isDoubleTy()) { 2660 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue()); 2661 } else if (Ty->isX86_FP80Ty()) { 2662 // api needed to prevent premature destruction 2663 // bits are not in the same order as a normal i80 APInt, compensate. 2664 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2665 const uint64_t *p = api.getRawData(); 2666 Record.push_back((p[1] << 48) | (p[0] >> 16)); 2667 Record.push_back(p[0] & 0xffffLL); 2668 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) { 2669 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2670 const uint64_t *p = api.getRawData(); 2671 Record.push_back(p[0]); 2672 Record.push_back(p[1]); 2673 } else { 2674 assert(0 && "Unknown FP type!"); 2675 } 2676 } else if (isa<ConstantDataSequential>(C) && 2677 cast<ConstantDataSequential>(C)->isString()) { 2678 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C); 2679 // Emit constant strings specially. 2680 unsigned NumElts = Str->getNumElements(); 2681 // If this is a null-terminated string, use the denser CSTRING encoding. 2682 if (Str->isCString()) { 2683 Code = bitc::CST_CODE_CSTRING; 2684 --NumElts; // Don't encode the null, which isn't allowed by char6. 2685 } else { 2686 Code = bitc::CST_CODE_STRING; 2687 AbbrevToUse = String8Abbrev; 2688 } 2689 bool isCStr7 = Code == bitc::CST_CODE_CSTRING; 2690 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; 2691 for (unsigned i = 0; i != NumElts; ++i) { 2692 unsigned char V = Str->getElementAsInteger(i); 2693 Record.push_back(V); 2694 isCStr7 &= (V & 128) == 0; 2695 if (isCStrChar6) 2696 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 2697 } 2698 2699 if (isCStrChar6) 2700 AbbrevToUse = CString6Abbrev; 2701 else if (isCStr7) 2702 AbbrevToUse = CString7Abbrev; 2703 } else if (const ConstantDataSequential *CDS = 2704 dyn_cast<ConstantDataSequential>(C)) { 2705 Code = bitc::CST_CODE_DATA; 2706 Type *EltTy = CDS->getElementType(); 2707 if (isa<IntegerType>(EltTy)) { 2708 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 2709 Record.push_back(CDS->getElementAsInteger(i)); 2710 } else { 2711 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 2712 Record.push_back( 2713 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue()); 2714 } 2715 } else if (isa<ConstantAggregate>(C)) { 2716 Code = bitc::CST_CODE_AGGREGATE; 2717 for (const Value *Op : C->operands()) 2718 Record.push_back(VE.getValueID(Op)); 2719 AbbrevToUse = AggregateAbbrev; 2720 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 2721 switch (CE->getOpcode()) { 2722 default: 2723 if (Instruction::isCast(CE->getOpcode())) { 2724 Code = bitc::CST_CODE_CE_CAST; 2725 Record.push_back(getEncodedCastOpcode(CE->getOpcode())); 2726 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2727 Record.push_back(VE.getValueID(C->getOperand(0))); 2728 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev; 2729 } else { 2730 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 2731 Code = bitc::CST_CODE_CE_BINOP; 2732 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode())); 2733 Record.push_back(VE.getValueID(C->getOperand(0))); 2734 Record.push_back(VE.getValueID(C->getOperand(1))); 2735 uint64_t Flags = getOptimizationFlags(CE); 2736 if (Flags != 0) 2737 Record.push_back(Flags); 2738 } 2739 break; 2740 case Instruction::FNeg: { 2741 assert(CE->getNumOperands() == 1 && "Unknown constant expr!"); 2742 Code = bitc::CST_CODE_CE_UNOP; 2743 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode())); 2744 Record.push_back(VE.getValueID(C->getOperand(0))); 2745 uint64_t Flags = getOptimizationFlags(CE); 2746 if (Flags != 0) 2747 Record.push_back(Flags); 2748 break; 2749 } 2750 case Instruction::GetElementPtr: { 2751 Code = bitc::CST_CODE_CE_GEP; 2752 const auto *GO = cast<GEPOperator>(C); 2753 Record.push_back(VE.getTypeID(GO->getSourceElementType())); 2754 if (std::optional<ConstantRange> Range = GO->getInRange()) { 2755 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE; 2756 Record.push_back(GO->isInBounds()); 2757 emitConstantRange(Record, *Range); 2758 } else if (GO->isInBounds()) 2759 Code = bitc::CST_CODE_CE_INBOUNDS_GEP; 2760 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 2761 Record.push_back(VE.getTypeID(C->getOperand(i)->getType())); 2762 Record.push_back(VE.getValueID(C->getOperand(i))); 2763 } 2764 break; 2765 } 2766 case Instruction::ExtractElement: 2767 Code = bitc::CST_CODE_CE_EXTRACTELT; 2768 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2769 Record.push_back(VE.getValueID(C->getOperand(0))); 2770 Record.push_back(VE.getTypeID(C->getOperand(1)->getType())); 2771 Record.push_back(VE.getValueID(C->getOperand(1))); 2772 break; 2773 case Instruction::InsertElement: 2774 Code = bitc::CST_CODE_CE_INSERTELT; 2775 Record.push_back(VE.getValueID(C->getOperand(0))); 2776 Record.push_back(VE.getValueID(C->getOperand(1))); 2777 Record.push_back(VE.getTypeID(C->getOperand(2)->getType())); 2778 Record.push_back(VE.getValueID(C->getOperand(2))); 2779 break; 2780 case Instruction::ShuffleVector: 2781 // If the return type and argument types are the same, this is a 2782 // standard shufflevector instruction. If the types are different, 2783 // then the shuffle is widening or truncating the input vectors, and 2784 // the argument type must also be encoded. 2785 if (C->getType() == C->getOperand(0)->getType()) { 2786 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 2787 } else { 2788 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 2789 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2790 } 2791 Record.push_back(VE.getValueID(C->getOperand(0))); 2792 Record.push_back(VE.getValueID(C->getOperand(1))); 2793 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode())); 2794 break; 2795 case Instruction::ICmp: 2796 case Instruction::FCmp: 2797 Code = bitc::CST_CODE_CE_CMP; 2798 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2799 Record.push_back(VE.getValueID(C->getOperand(0))); 2800 Record.push_back(VE.getValueID(C->getOperand(1))); 2801 Record.push_back(CE->getPredicate()); 2802 break; 2803 } 2804 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) { 2805 Code = bitc::CST_CODE_BLOCKADDRESS; 2806 Record.push_back(VE.getTypeID(BA->getFunction()->getType())); 2807 Record.push_back(VE.getValueID(BA->getFunction())); 2808 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock())); 2809 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) { 2810 Code = bitc::CST_CODE_DSO_LOCAL_EQUIVALENT; 2811 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType())); 2812 Record.push_back(VE.getValueID(Equiv->getGlobalValue())); 2813 } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) { 2814 Code = bitc::CST_CODE_NO_CFI_VALUE; 2815 Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType())); 2816 Record.push_back(VE.getValueID(NC->getGlobalValue())); 2817 } else { 2818 #ifndef NDEBUG 2819 C->dump(); 2820 #endif 2821 llvm_unreachable("Unknown constant!"); 2822 } 2823 Stream.EmitRecord(Code, Record, AbbrevToUse); 2824 Record.clear(); 2825 } 2826 2827 Stream.ExitBlock(); 2828 } 2829 2830 void ModuleBitcodeWriter::writeModuleConstants() { 2831 const ValueEnumerator::ValueList &Vals = VE.getValues(); 2832 2833 // Find the first constant to emit, which is the first non-globalvalue value. 2834 // We know globalvalues have been emitted by WriteModuleInfo. 2835 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 2836 if (!isa<GlobalValue>(Vals[i].first)) { 2837 writeConstants(i, Vals.size(), true); 2838 return; 2839 } 2840 } 2841 } 2842 2843 /// pushValueAndType - The file has to encode both the value and type id for 2844 /// many values, because we need to know what type to create for forward 2845 /// references. However, most operands are not forward references, so this type 2846 /// field is not needed. 2847 /// 2848 /// This function adds V's value ID to Vals. If the value ID is higher than the 2849 /// instruction ID, then it is a forward reference, and it also includes the 2850 /// type ID. The value ID that is written is encoded relative to the InstID. 2851 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID, 2852 SmallVectorImpl<unsigned> &Vals) { 2853 unsigned ValID = VE.getValueID(V); 2854 // Make encoding relative to the InstID. 2855 Vals.push_back(InstID - ValID); 2856 if (ValID >= InstID) { 2857 Vals.push_back(VE.getTypeID(V->getType())); 2858 return true; 2859 } 2860 return false; 2861 } 2862 2863 void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS, 2864 unsigned InstID) { 2865 SmallVector<unsigned, 64> Record; 2866 LLVMContext &C = CS.getContext(); 2867 2868 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) { 2869 const auto &Bundle = CS.getOperandBundleAt(i); 2870 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName())); 2871 2872 for (auto &Input : Bundle.Inputs) 2873 pushValueAndType(Input, InstID, Record); 2874 2875 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record); 2876 Record.clear(); 2877 } 2878 } 2879 2880 /// pushValue - Like pushValueAndType, but where the type of the value is 2881 /// omitted (perhaps it was already encoded in an earlier operand). 2882 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID, 2883 SmallVectorImpl<unsigned> &Vals) { 2884 unsigned ValID = VE.getValueID(V); 2885 Vals.push_back(InstID - ValID); 2886 } 2887 2888 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID, 2889 SmallVectorImpl<uint64_t> &Vals) { 2890 unsigned ValID = VE.getValueID(V); 2891 int64_t diff = ((int32_t)InstID - (int32_t)ValID); 2892 emitSignedInt64(Vals, diff); 2893 } 2894 2895 /// WriteInstruction - Emit an instruction to the specified stream. 2896 void ModuleBitcodeWriter::writeInstruction(const Instruction &I, 2897 unsigned InstID, 2898 SmallVectorImpl<unsigned> &Vals) { 2899 unsigned Code = 0; 2900 unsigned AbbrevToUse = 0; 2901 VE.setInstructionID(&I); 2902 switch (I.getOpcode()) { 2903 default: 2904 if (Instruction::isCast(I.getOpcode())) { 2905 Code = bitc::FUNC_CODE_INST_CAST; 2906 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2907 AbbrevToUse = FUNCTION_INST_CAST_ABBREV; 2908 Vals.push_back(VE.getTypeID(I.getType())); 2909 Vals.push_back(getEncodedCastOpcode(I.getOpcode())); 2910 uint64_t Flags = getOptimizationFlags(&I); 2911 if (Flags != 0) { 2912 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV) 2913 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV; 2914 Vals.push_back(Flags); 2915 } 2916 } else { 2917 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 2918 Code = bitc::FUNC_CODE_INST_BINOP; 2919 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2920 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV; 2921 pushValue(I.getOperand(1), InstID, Vals); 2922 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode())); 2923 uint64_t Flags = getOptimizationFlags(&I); 2924 if (Flags != 0) { 2925 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV) 2926 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV; 2927 Vals.push_back(Flags); 2928 } 2929 } 2930 break; 2931 case Instruction::FNeg: { 2932 Code = bitc::FUNC_CODE_INST_UNOP; 2933 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2934 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV; 2935 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode())); 2936 uint64_t Flags = getOptimizationFlags(&I); 2937 if (Flags != 0) { 2938 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV) 2939 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV; 2940 Vals.push_back(Flags); 2941 } 2942 break; 2943 } 2944 case Instruction::GetElementPtr: { 2945 Code = bitc::FUNC_CODE_INST_GEP; 2946 AbbrevToUse = FUNCTION_INST_GEP_ABBREV; 2947 auto &GEPInst = cast<GetElementPtrInst>(I); 2948 Vals.push_back(GEPInst.isInBounds()); 2949 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType())); 2950 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 2951 pushValueAndType(I.getOperand(i), InstID, Vals); 2952 break; 2953 } 2954 case Instruction::ExtractValue: { 2955 Code = bitc::FUNC_CODE_INST_EXTRACTVAL; 2956 pushValueAndType(I.getOperand(0), InstID, Vals); 2957 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I); 2958 Vals.append(EVI->idx_begin(), EVI->idx_end()); 2959 break; 2960 } 2961 case Instruction::InsertValue: { 2962 Code = bitc::FUNC_CODE_INST_INSERTVAL; 2963 pushValueAndType(I.getOperand(0), InstID, Vals); 2964 pushValueAndType(I.getOperand(1), InstID, Vals); 2965 const InsertValueInst *IVI = cast<InsertValueInst>(&I); 2966 Vals.append(IVI->idx_begin(), IVI->idx_end()); 2967 break; 2968 } 2969 case Instruction::Select: { 2970 Code = bitc::FUNC_CODE_INST_VSELECT; 2971 pushValueAndType(I.getOperand(1), InstID, Vals); 2972 pushValue(I.getOperand(2), InstID, Vals); 2973 pushValueAndType(I.getOperand(0), InstID, Vals); 2974 uint64_t Flags = getOptimizationFlags(&I); 2975 if (Flags != 0) 2976 Vals.push_back(Flags); 2977 break; 2978 } 2979 case Instruction::ExtractElement: 2980 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 2981 pushValueAndType(I.getOperand(0), InstID, Vals); 2982 pushValueAndType(I.getOperand(1), InstID, Vals); 2983 break; 2984 case Instruction::InsertElement: 2985 Code = bitc::FUNC_CODE_INST_INSERTELT; 2986 pushValueAndType(I.getOperand(0), InstID, Vals); 2987 pushValue(I.getOperand(1), InstID, Vals); 2988 pushValueAndType(I.getOperand(2), InstID, Vals); 2989 break; 2990 case Instruction::ShuffleVector: 2991 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 2992 pushValueAndType(I.getOperand(0), InstID, Vals); 2993 pushValue(I.getOperand(1), InstID, Vals); 2994 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID, 2995 Vals); 2996 break; 2997 case Instruction::ICmp: 2998 case Instruction::FCmp: { 2999 // compare returning Int1Ty or vector of Int1Ty 3000 Code = bitc::FUNC_CODE_INST_CMP2; 3001 pushValueAndType(I.getOperand(0), InstID, Vals); 3002 pushValue(I.getOperand(1), InstID, Vals); 3003 Vals.push_back(cast<CmpInst>(I).getPredicate()); 3004 uint64_t Flags = getOptimizationFlags(&I); 3005 if (Flags != 0) 3006 Vals.push_back(Flags); 3007 break; 3008 } 3009 3010 case Instruction::Ret: 3011 { 3012 Code = bitc::FUNC_CODE_INST_RET; 3013 unsigned NumOperands = I.getNumOperands(); 3014 if (NumOperands == 0) 3015 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV; 3016 else if (NumOperands == 1) { 3017 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 3018 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV; 3019 } else { 3020 for (unsigned i = 0, e = NumOperands; i != e; ++i) 3021 pushValueAndType(I.getOperand(i), InstID, Vals); 3022 } 3023 } 3024 break; 3025 case Instruction::Br: 3026 { 3027 Code = bitc::FUNC_CODE_INST_BR; 3028 const BranchInst &II = cast<BranchInst>(I); 3029 Vals.push_back(VE.getValueID(II.getSuccessor(0))); 3030 if (II.isConditional()) { 3031 Vals.push_back(VE.getValueID(II.getSuccessor(1))); 3032 pushValue(II.getCondition(), InstID, Vals); 3033 } 3034 } 3035 break; 3036 case Instruction::Switch: 3037 { 3038 Code = bitc::FUNC_CODE_INST_SWITCH; 3039 const SwitchInst &SI = cast<SwitchInst>(I); 3040 Vals.push_back(VE.getTypeID(SI.getCondition()->getType())); 3041 pushValue(SI.getCondition(), InstID, Vals); 3042 Vals.push_back(VE.getValueID(SI.getDefaultDest())); 3043 for (auto Case : SI.cases()) { 3044 Vals.push_back(VE.getValueID(Case.getCaseValue())); 3045 Vals.push_back(VE.getValueID(Case.getCaseSuccessor())); 3046 } 3047 } 3048 break; 3049 case Instruction::IndirectBr: 3050 Code = bitc::FUNC_CODE_INST_INDIRECTBR; 3051 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 3052 // Encode the address operand as relative, but not the basic blocks. 3053 pushValue(I.getOperand(0), InstID, Vals); 3054 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) 3055 Vals.push_back(VE.getValueID(I.getOperand(i))); 3056 break; 3057 3058 case Instruction::Invoke: { 3059 const InvokeInst *II = cast<InvokeInst>(&I); 3060 const Value *Callee = II->getCalledOperand(); 3061 FunctionType *FTy = II->getFunctionType(); 3062 3063 if (II->hasOperandBundles()) 3064 writeOperandBundles(*II, InstID); 3065 3066 Code = bitc::FUNC_CODE_INST_INVOKE; 3067 3068 Vals.push_back(VE.getAttributeListID(II->getAttributes())); 3069 Vals.push_back(II->getCallingConv() | 1 << 13); 3070 Vals.push_back(VE.getValueID(II->getNormalDest())); 3071 Vals.push_back(VE.getValueID(II->getUnwindDest())); 3072 Vals.push_back(VE.getTypeID(FTy)); 3073 pushValueAndType(Callee, InstID, Vals); 3074 3075 // Emit value #'s for the fixed parameters. 3076 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 3077 pushValue(I.getOperand(i), InstID, Vals); // fixed param. 3078 3079 // Emit type/value pairs for varargs params. 3080 if (FTy->isVarArg()) { 3081 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i) 3082 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg 3083 } 3084 break; 3085 } 3086 case Instruction::Resume: 3087 Code = bitc::FUNC_CODE_INST_RESUME; 3088 pushValueAndType(I.getOperand(0), InstID, Vals); 3089 break; 3090 case Instruction::CleanupRet: { 3091 Code = bitc::FUNC_CODE_INST_CLEANUPRET; 3092 const auto &CRI = cast<CleanupReturnInst>(I); 3093 pushValue(CRI.getCleanupPad(), InstID, Vals); 3094 if (CRI.hasUnwindDest()) 3095 Vals.push_back(VE.getValueID(CRI.getUnwindDest())); 3096 break; 3097 } 3098 case Instruction::CatchRet: { 3099 Code = bitc::FUNC_CODE_INST_CATCHRET; 3100 const auto &CRI = cast<CatchReturnInst>(I); 3101 pushValue(CRI.getCatchPad(), InstID, Vals); 3102 Vals.push_back(VE.getValueID(CRI.getSuccessor())); 3103 break; 3104 } 3105 case Instruction::CleanupPad: 3106 case Instruction::CatchPad: { 3107 const auto &FuncletPad = cast<FuncletPadInst>(I); 3108 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD 3109 : bitc::FUNC_CODE_INST_CLEANUPPAD; 3110 pushValue(FuncletPad.getParentPad(), InstID, Vals); 3111 3112 unsigned NumArgOperands = FuncletPad.arg_size(); 3113 Vals.push_back(NumArgOperands); 3114 for (unsigned Op = 0; Op != NumArgOperands; ++Op) 3115 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals); 3116 break; 3117 } 3118 case Instruction::CatchSwitch: { 3119 Code = bitc::FUNC_CODE_INST_CATCHSWITCH; 3120 const auto &CatchSwitch = cast<CatchSwitchInst>(I); 3121 3122 pushValue(CatchSwitch.getParentPad(), InstID, Vals); 3123 3124 unsigned NumHandlers = CatchSwitch.getNumHandlers(); 3125 Vals.push_back(NumHandlers); 3126 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers()) 3127 Vals.push_back(VE.getValueID(CatchPadBB)); 3128 3129 if (CatchSwitch.hasUnwindDest()) 3130 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest())); 3131 break; 3132 } 3133 case Instruction::CallBr: { 3134 const CallBrInst *CBI = cast<CallBrInst>(&I); 3135 const Value *Callee = CBI->getCalledOperand(); 3136 FunctionType *FTy = CBI->getFunctionType(); 3137 3138 if (CBI->hasOperandBundles()) 3139 writeOperandBundles(*CBI, InstID); 3140 3141 Code = bitc::FUNC_CODE_INST_CALLBR; 3142 3143 Vals.push_back(VE.getAttributeListID(CBI->getAttributes())); 3144 3145 Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV | 3146 1 << bitc::CALL_EXPLICIT_TYPE); 3147 3148 Vals.push_back(VE.getValueID(CBI->getDefaultDest())); 3149 Vals.push_back(CBI->getNumIndirectDests()); 3150 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) 3151 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i))); 3152 3153 Vals.push_back(VE.getTypeID(FTy)); 3154 pushValueAndType(Callee, InstID, Vals); 3155 3156 // Emit value #'s for the fixed parameters. 3157 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 3158 pushValue(I.getOperand(i), InstID, Vals); // fixed param. 3159 3160 // Emit type/value pairs for varargs params. 3161 if (FTy->isVarArg()) { 3162 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i) 3163 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg 3164 } 3165 break; 3166 } 3167 case Instruction::Unreachable: 3168 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 3169 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV; 3170 break; 3171 3172 case Instruction::PHI: { 3173 const PHINode &PN = cast<PHINode>(I); 3174 Code = bitc::FUNC_CODE_INST_PHI; 3175 // With the newer instruction encoding, forward references could give 3176 // negative valued IDs. This is most common for PHIs, so we use 3177 // signed VBRs. 3178 SmallVector<uint64_t, 128> Vals64; 3179 Vals64.push_back(VE.getTypeID(PN.getType())); 3180 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 3181 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64); 3182 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i))); 3183 } 3184 3185 uint64_t Flags = getOptimizationFlags(&I); 3186 if (Flags != 0) 3187 Vals64.push_back(Flags); 3188 3189 // Emit a Vals64 vector and exit. 3190 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 3191 Vals64.clear(); 3192 return; 3193 } 3194 3195 case Instruction::LandingPad: { 3196 const LandingPadInst &LP = cast<LandingPadInst>(I); 3197 Code = bitc::FUNC_CODE_INST_LANDINGPAD; 3198 Vals.push_back(VE.getTypeID(LP.getType())); 3199 Vals.push_back(LP.isCleanup()); 3200 Vals.push_back(LP.getNumClauses()); 3201 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) { 3202 if (LP.isCatch(I)) 3203 Vals.push_back(LandingPadInst::Catch); 3204 else 3205 Vals.push_back(LandingPadInst::Filter); 3206 pushValueAndType(LP.getClause(I), InstID, Vals); 3207 } 3208 break; 3209 } 3210 3211 case Instruction::Alloca: { 3212 Code = bitc::FUNC_CODE_INST_ALLOCA; 3213 const AllocaInst &AI = cast<AllocaInst>(I); 3214 Vals.push_back(VE.getTypeID(AI.getAllocatedType())); 3215 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 3216 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 3217 using APV = AllocaPackedValues; 3218 unsigned Record = 0; 3219 unsigned EncodedAlign = getEncodedAlign(AI.getAlign()); 3220 Bitfield::set<APV::AlignLower>( 3221 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1)); 3222 Bitfield::set<APV::AlignUpper>(Record, 3223 EncodedAlign >> APV::AlignLower::Bits); 3224 Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca()); 3225 Bitfield::set<APV::ExplicitType>(Record, true); 3226 Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError()); 3227 Vals.push_back(Record); 3228 3229 unsigned AS = AI.getAddressSpace(); 3230 if (AS != M.getDataLayout().getAllocaAddrSpace()) 3231 Vals.push_back(AS); 3232 break; 3233 } 3234 3235 case Instruction::Load: 3236 if (cast<LoadInst>(I).isAtomic()) { 3237 Code = bitc::FUNC_CODE_INST_LOADATOMIC; 3238 pushValueAndType(I.getOperand(0), InstID, Vals); 3239 } else { 3240 Code = bitc::FUNC_CODE_INST_LOAD; 3241 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr 3242 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV; 3243 } 3244 Vals.push_back(VE.getTypeID(I.getType())); 3245 Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign())); 3246 Vals.push_back(cast<LoadInst>(I).isVolatile()); 3247 if (cast<LoadInst>(I).isAtomic()) { 3248 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering())); 3249 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID())); 3250 } 3251 break; 3252 case Instruction::Store: 3253 if (cast<StoreInst>(I).isAtomic()) 3254 Code = bitc::FUNC_CODE_INST_STOREATOMIC; 3255 else 3256 Code = bitc::FUNC_CODE_INST_STORE; 3257 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr 3258 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val 3259 Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign())); 3260 Vals.push_back(cast<StoreInst>(I).isVolatile()); 3261 if (cast<StoreInst>(I).isAtomic()) { 3262 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering())); 3263 Vals.push_back( 3264 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID())); 3265 } 3266 break; 3267 case Instruction::AtomicCmpXchg: 3268 Code = bitc::FUNC_CODE_INST_CMPXCHG; 3269 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 3270 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp. 3271 pushValue(I.getOperand(2), InstID, Vals); // newval. 3272 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile()); 3273 Vals.push_back( 3274 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering())); 3275 Vals.push_back( 3276 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID())); 3277 Vals.push_back( 3278 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering())); 3279 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak()); 3280 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign())); 3281 break; 3282 case Instruction::AtomicRMW: 3283 Code = bitc::FUNC_CODE_INST_ATOMICRMW; 3284 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 3285 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val 3286 Vals.push_back( 3287 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation())); 3288 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile()); 3289 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering())); 3290 Vals.push_back( 3291 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID())); 3292 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign())); 3293 break; 3294 case Instruction::Fence: 3295 Code = bitc::FUNC_CODE_INST_FENCE; 3296 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering())); 3297 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID())); 3298 break; 3299 case Instruction::Call: { 3300 const CallInst &CI = cast<CallInst>(I); 3301 FunctionType *FTy = CI.getFunctionType(); 3302 3303 if (CI.hasOperandBundles()) 3304 writeOperandBundles(CI, InstID); 3305 3306 Code = bitc::FUNC_CODE_INST_CALL; 3307 3308 Vals.push_back(VE.getAttributeListID(CI.getAttributes())); 3309 3310 unsigned Flags = getOptimizationFlags(&I); 3311 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV | 3312 unsigned(CI.isTailCall()) << bitc::CALL_TAIL | 3313 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL | 3314 1 << bitc::CALL_EXPLICIT_TYPE | 3315 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL | 3316 unsigned(Flags != 0) << bitc::CALL_FMF); 3317 if (Flags != 0) 3318 Vals.push_back(Flags); 3319 3320 Vals.push_back(VE.getTypeID(FTy)); 3321 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee 3322 3323 // Emit value #'s for the fixed parameters. 3324 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 3325 // Check for labels (can happen with asm labels). 3326 if (FTy->getParamType(i)->isLabelTy()) 3327 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); 3328 else 3329 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param. 3330 } 3331 3332 // Emit type/value pairs for varargs params. 3333 if (FTy->isVarArg()) { 3334 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i) 3335 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs 3336 } 3337 break; 3338 } 3339 case Instruction::VAArg: 3340 Code = bitc::FUNC_CODE_INST_VAARG; 3341 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty 3342 pushValue(I.getOperand(0), InstID, Vals); // valist. 3343 Vals.push_back(VE.getTypeID(I.getType())); // restype. 3344 break; 3345 case Instruction::Freeze: 3346 Code = bitc::FUNC_CODE_INST_FREEZE; 3347 pushValueAndType(I.getOperand(0), InstID, Vals); 3348 break; 3349 } 3350 3351 Stream.EmitRecord(Code, Vals, AbbrevToUse); 3352 Vals.clear(); 3353 } 3354 3355 /// Write a GlobalValue VST to the module. The purpose of this data structure is 3356 /// to allow clients to efficiently find the function body. 3357 void ModuleBitcodeWriter::writeGlobalValueSymbolTable( 3358 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) { 3359 // Get the offset of the VST we are writing, and backpatch it into 3360 // the VST forward declaration record. 3361 uint64_t VSTOffset = Stream.GetCurrentBitNo(); 3362 // The BitcodeStartBit was the stream offset of the identification block. 3363 VSTOffset -= bitcodeStartBit(); 3364 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned"); 3365 // Note that we add 1 here because the offset is relative to one word 3366 // before the start of the identification block, which was historically 3367 // always the start of the regular bitcode header. 3368 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1); 3369 3370 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 3371 3372 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3373 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY)); 3374 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 3375 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset 3376 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3377 3378 for (const Function &F : M) { 3379 uint64_t Record[2]; 3380 3381 if (F.isDeclaration()) 3382 continue; 3383 3384 Record[0] = VE.getValueID(&F); 3385 3386 // Save the word offset of the function (from the start of the 3387 // actual bitcode written to the stream). 3388 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit(); 3389 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned"); 3390 // Note that we add 1 here because the offset is relative to one word 3391 // before the start of the identification block, which was historically 3392 // always the start of the regular bitcode header. 3393 Record[1] = BitcodeIndex / 32 + 1; 3394 3395 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev); 3396 } 3397 3398 Stream.ExitBlock(); 3399 } 3400 3401 /// Emit names for arguments, instructions and basic blocks in a function. 3402 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable( 3403 const ValueSymbolTable &VST) { 3404 if (VST.empty()) 3405 return; 3406 3407 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 3408 3409 // FIXME: Set up the abbrev, we know how many values there are! 3410 // FIXME: We know if the type names can use 7-bit ascii. 3411 SmallVector<uint64_t, 64> NameVals; 3412 3413 for (const ValueName &Name : VST) { 3414 // Figure out the encoding to use for the name. 3415 StringEncoding Bits = getStringEncoding(Name.getKey()); 3416 3417 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 3418 NameVals.push_back(VE.getValueID(Name.getValue())); 3419 3420 // VST_CODE_ENTRY: [valueid, namechar x N] 3421 // VST_CODE_BBENTRY: [bbid, namechar x N] 3422 unsigned Code; 3423 if (isa<BasicBlock>(Name.getValue())) { 3424 Code = bitc::VST_CODE_BBENTRY; 3425 if (Bits == SE_Char6) 3426 AbbrevToUse = VST_BBENTRY_6_ABBREV; 3427 } else { 3428 Code = bitc::VST_CODE_ENTRY; 3429 if (Bits == SE_Char6) 3430 AbbrevToUse = VST_ENTRY_6_ABBREV; 3431 else if (Bits == SE_Fixed7) 3432 AbbrevToUse = VST_ENTRY_7_ABBREV; 3433 } 3434 3435 for (const auto P : Name.getKey()) 3436 NameVals.push_back((unsigned char)P); 3437 3438 // Emit the finished record. 3439 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 3440 NameVals.clear(); 3441 } 3442 3443 Stream.ExitBlock(); 3444 } 3445 3446 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) { 3447 assert(Order.Shuffle.size() >= 2 && "Shuffle too small"); 3448 unsigned Code; 3449 if (isa<BasicBlock>(Order.V)) 3450 Code = bitc::USELIST_CODE_BB; 3451 else 3452 Code = bitc::USELIST_CODE_DEFAULT; 3453 3454 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end()); 3455 Record.push_back(VE.getValueID(Order.V)); 3456 Stream.EmitRecord(Code, Record); 3457 } 3458 3459 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) { 3460 assert(VE.shouldPreserveUseListOrder() && 3461 "Expected to be preserving use-list order"); 3462 3463 auto hasMore = [&]() { 3464 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F; 3465 }; 3466 if (!hasMore()) 3467 // Nothing to do. 3468 return; 3469 3470 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3); 3471 while (hasMore()) { 3472 writeUseList(std::move(VE.UseListOrders.back())); 3473 VE.UseListOrders.pop_back(); 3474 } 3475 Stream.ExitBlock(); 3476 } 3477 3478 /// Emit a function body to the module stream. 3479 void ModuleBitcodeWriter::writeFunction( 3480 const Function &F, 3481 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) { 3482 // Save the bitcode index of the start of this function block for recording 3483 // in the VST. 3484 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo(); 3485 3486 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 3487 VE.incorporateFunction(F); 3488 3489 SmallVector<unsigned, 64> Vals; 3490 3491 // Emit the number of basic blocks, so the reader can create them ahead of 3492 // time. 3493 Vals.push_back(VE.getBasicBlocks().size()); 3494 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 3495 Vals.clear(); 3496 3497 // If there are function-local constants, emit them now. 3498 unsigned CstStart, CstEnd; 3499 VE.getFunctionConstantRange(CstStart, CstEnd); 3500 writeConstants(CstStart, CstEnd, false); 3501 3502 // If there is function-local metadata, emit it now. 3503 writeFunctionMetadata(F); 3504 3505 // Keep a running idea of what the instruction ID is. 3506 unsigned InstID = CstEnd; 3507 3508 bool NeedsMetadataAttachment = F.hasMetadata(); 3509 3510 DILocation *LastDL = nullptr; 3511 SmallSetVector<Function *, 4> BlockAddressUsers; 3512 3513 // Finally, emit all the instructions, in order. 3514 for (const BasicBlock &BB : F) { 3515 for (const Instruction &I : BB) { 3516 writeInstruction(I, InstID, Vals); 3517 3518 if (!I.getType()->isVoidTy()) 3519 ++InstID; 3520 3521 // If the instruction has metadata, write a metadata attachment later. 3522 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc(); 3523 3524 // If the instruction has a debug location, emit it. 3525 if (DILocation *DL = I.getDebugLoc()) { 3526 if (DL == LastDL) { 3527 // Just repeat the same debug loc as last time. 3528 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals); 3529 } else { 3530 Vals.push_back(DL->getLine()); 3531 Vals.push_back(DL->getColumn()); 3532 Vals.push_back(VE.getMetadataOrNullID(DL->getScope())); 3533 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt())); 3534 Vals.push_back(DL->isImplicitCode()); 3535 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals); 3536 Vals.clear(); 3537 LastDL = DL; 3538 } 3539 } 3540 3541 // If the instruction has DbgRecords attached to it, emit them. Note that 3542 // they come after the instruction so that it's easy to attach them again 3543 // when reading the bitcode, even though conceptually the debug locations 3544 // start "before" the instruction. 3545 if (I.hasDbgRecords() && WriteNewDbgInfoFormatToBitcode) { 3546 /// Try to push the value only (unwrapped), otherwise push the 3547 /// metadata wrapped value. Returns true if the value was pushed 3548 /// without the ValueAsMetadata wrapper. 3549 auto PushValueOrMetadata = [&Vals, InstID, 3550 this](Metadata *RawLocation) { 3551 assert(RawLocation && 3552 "RawLocation unexpectedly null in DbgVariableRecord"); 3553 if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) { 3554 SmallVector<unsigned, 2> ValAndType; 3555 // If the value is a fwd-ref the type is also pushed. We don't 3556 // want the type, so fwd-refs are kept wrapped (pushValueAndType 3557 // returns false if the value is pushed without type). 3558 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) { 3559 Vals.push_back(ValAndType[0]); 3560 return true; 3561 } 3562 } 3563 // The metadata is a DIArgList, or ValueAsMetadata wrapping a 3564 // fwd-ref. Push the metadata ID. 3565 Vals.push_back(VE.getMetadataID(RawLocation)); 3566 return false; 3567 }; 3568 3569 // Write out non-instruction debug information attached to this 3570 // instruction. Write it after the instruction so that it's easy to 3571 // re-attach to the instruction reading the records in. 3572 for (DbgRecord &DR : I.DbgMarker->getDbgRecordRange()) { 3573 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) { 3574 Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc())); 3575 Vals.push_back(VE.getMetadataID(DLR->getLabel())); 3576 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_LABEL, Vals); 3577 Vals.clear(); 3578 continue; 3579 } 3580 3581 // First 3 fields are common to all kinds: 3582 // DILocation, DILocalVariable, DIExpression 3583 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE) 3584 // ..., LocationMetadata 3585 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd) 3586 // ..., Value 3587 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE) 3588 // ..., LocationMetadata 3589 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN) 3590 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata 3591 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR); 3592 Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc())); 3593 Vals.push_back(VE.getMetadataID(DVR.getVariable())); 3594 Vals.push_back(VE.getMetadataID(DVR.getExpression())); 3595 if (DVR.isDbgValue()) { 3596 if (PushValueOrMetadata(DVR.getRawLocation())) 3597 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE, Vals, 3598 FUNCTION_DEBUG_RECORD_VALUE_ABBREV); 3599 else 3600 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_VALUE, Vals); 3601 } else if (DVR.isDbgDeclare()) { 3602 Vals.push_back(VE.getMetadataID(DVR.getRawLocation())); 3603 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_DECLARE, Vals); 3604 } else { 3605 assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind"); 3606 Vals.push_back(VE.getMetadataID(DVR.getRawLocation())); 3607 Vals.push_back(VE.getMetadataID(DVR.getAssignID())); 3608 Vals.push_back(VE.getMetadataID(DVR.getAddressExpression())); 3609 Vals.push_back(VE.getMetadataID(DVR.getRawAddress())); 3610 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN, Vals); 3611 } 3612 Vals.clear(); 3613 } 3614 } 3615 } 3616 3617 if (BlockAddress *BA = BlockAddress::lookup(&BB)) { 3618 SmallVector<Value *> Worklist{BA}; 3619 SmallPtrSet<Value *, 8> Visited{BA}; 3620 while (!Worklist.empty()) { 3621 Value *V = Worklist.pop_back_val(); 3622 for (User *U : V->users()) { 3623 if (auto *I = dyn_cast<Instruction>(U)) { 3624 Function *P = I->getFunction(); 3625 if (P != &F) 3626 BlockAddressUsers.insert(P); 3627 } else if (isa<Constant>(U) && !isa<GlobalValue>(U) && 3628 Visited.insert(U).second) 3629 Worklist.push_back(U); 3630 } 3631 } 3632 } 3633 } 3634 3635 if (!BlockAddressUsers.empty()) { 3636 Vals.resize(BlockAddressUsers.size()); 3637 for (auto I : llvm::enumerate(BlockAddressUsers)) 3638 Vals[I.index()] = VE.getValueID(I.value()); 3639 Stream.EmitRecord(bitc::FUNC_CODE_BLOCKADDR_USERS, Vals); 3640 Vals.clear(); 3641 } 3642 3643 // Emit names for all the instructions etc. 3644 if (auto *Symtab = F.getValueSymbolTable()) 3645 writeFunctionLevelValueSymbolTable(*Symtab); 3646 3647 if (NeedsMetadataAttachment) 3648 writeFunctionMetadataAttachment(F); 3649 if (VE.shouldPreserveUseListOrder()) 3650 writeUseListBlock(&F); 3651 VE.purgeFunction(); 3652 Stream.ExitBlock(); 3653 } 3654 3655 // Emit blockinfo, which defines the standard abbreviations etc. 3656 void ModuleBitcodeWriter::writeBlockInfo() { 3657 // We only want to emit block info records for blocks that have multiple 3658 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. 3659 // Other blocks can define their abbrevs inline. 3660 Stream.EnterBlockInfoBlock(); 3661 3662 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings. 3663 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3664 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 3665 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3666 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3667 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 3668 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3669 VST_ENTRY_8_ABBREV) 3670 llvm_unreachable("Unexpected abbrev ordering!"); 3671 } 3672 3673 { // 7-bit fixed width VST_CODE_ENTRY strings. 3674 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3675 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 3676 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3677 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3678 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 3679 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3680 VST_ENTRY_7_ABBREV) 3681 llvm_unreachable("Unexpected abbrev ordering!"); 3682 } 3683 { // 6-bit char6 VST_CODE_ENTRY strings. 3684 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3685 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 3686 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3687 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3688 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3689 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3690 VST_ENTRY_6_ABBREV) 3691 llvm_unreachable("Unexpected abbrev ordering!"); 3692 } 3693 { // 6-bit char6 VST_CODE_BBENTRY strings. 3694 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3695 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY)); 3696 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3697 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3698 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3699 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3700 VST_BBENTRY_6_ABBREV) 3701 llvm_unreachable("Unexpected abbrev ordering!"); 3702 } 3703 3704 { // SETTYPE abbrev for CONSTANTS_BLOCK. 3705 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3706 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); 3707 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3708 VE.computeBitsRequiredForTypeIndicies())); 3709 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3710 CONSTANTS_SETTYPE_ABBREV) 3711 llvm_unreachable("Unexpected abbrev ordering!"); 3712 } 3713 3714 { // INTEGER abbrev for CONSTANTS_BLOCK. 3715 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3716 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); 3717 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3718 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3719 CONSTANTS_INTEGER_ABBREV) 3720 llvm_unreachable("Unexpected abbrev ordering!"); 3721 } 3722 3723 { // CE_CAST abbrev for CONSTANTS_BLOCK. 3724 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3725 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); 3726 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc 3727 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid 3728 VE.computeBitsRequiredForTypeIndicies())); 3729 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 3730 3731 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3732 CONSTANTS_CE_CAST_Abbrev) 3733 llvm_unreachable("Unexpected abbrev ordering!"); 3734 } 3735 { // NULL abbrev for CONSTANTS_BLOCK. 3736 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3737 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL)); 3738 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3739 CONSTANTS_NULL_Abbrev) 3740 llvm_unreachable("Unexpected abbrev ordering!"); 3741 } 3742 3743 // FIXME: This should only use space for first class types! 3744 3745 { // INST_LOAD abbrev for FUNCTION_BLOCK. 3746 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3747 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); 3748 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr 3749 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3750 VE.computeBitsRequiredForTypeIndicies())); 3751 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align 3752 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile 3753 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3754 FUNCTION_INST_LOAD_ABBREV) 3755 llvm_unreachable("Unexpected abbrev ordering!"); 3756 } 3757 { // INST_UNOP abbrev for FUNCTION_BLOCK. 3758 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3759 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP)); 3760 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3761 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3762 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3763 FUNCTION_INST_UNOP_ABBREV) 3764 llvm_unreachable("Unexpected abbrev ordering!"); 3765 } 3766 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK. 3767 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3768 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP)); 3769 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3770 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3771 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags 3772 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3773 FUNCTION_INST_UNOP_FLAGS_ABBREV) 3774 llvm_unreachable("Unexpected abbrev ordering!"); 3775 } 3776 { // INST_BINOP abbrev for FUNCTION_BLOCK. 3777 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3778 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 3779 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3780 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 3781 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3782 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3783 FUNCTION_INST_BINOP_ABBREV) 3784 llvm_unreachable("Unexpected abbrev ordering!"); 3785 } 3786 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK. 3787 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3788 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 3789 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3790 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 3791 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3792 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags 3793 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3794 FUNCTION_INST_BINOP_FLAGS_ABBREV) 3795 llvm_unreachable("Unexpected abbrev ordering!"); 3796 } 3797 { // INST_CAST abbrev for FUNCTION_BLOCK. 3798 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3799 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 3800 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 3801 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3802 VE.computeBitsRequiredForTypeIndicies())); 3803 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3804 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3805 FUNCTION_INST_CAST_ABBREV) 3806 llvm_unreachable("Unexpected abbrev ordering!"); 3807 } 3808 { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK. 3809 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3810 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 3811 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 3812 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3813 VE.computeBitsRequiredForTypeIndicies())); 3814 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3815 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags 3816 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3817 FUNCTION_INST_CAST_FLAGS_ABBREV) 3818 llvm_unreachable("Unexpected abbrev ordering!"); 3819 } 3820 3821 { // INST_RET abbrev for FUNCTION_BLOCK. 3822 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3823 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 3824 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3825 FUNCTION_INST_RET_VOID_ABBREV) 3826 llvm_unreachable("Unexpected abbrev ordering!"); 3827 } 3828 { // INST_RET abbrev for FUNCTION_BLOCK. 3829 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3830 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 3831 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID 3832 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3833 FUNCTION_INST_RET_VAL_ABBREV) 3834 llvm_unreachable("Unexpected abbrev ordering!"); 3835 } 3836 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK. 3837 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3838 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE)); 3839 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3840 FUNCTION_INST_UNREACHABLE_ABBREV) 3841 llvm_unreachable("Unexpected abbrev ordering!"); 3842 } 3843 { 3844 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3845 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP)); 3846 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 3847 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3848 Log2_32_Ceil(VE.getTypes().size() + 1))); 3849 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3850 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 3851 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3852 FUNCTION_INST_GEP_ABBREV) 3853 llvm_unreachable("Unexpected abbrev ordering!"); 3854 } 3855 { 3856 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3857 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE)); 3858 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc 3859 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var 3860 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr 3861 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // val 3862 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3863 FUNCTION_DEBUG_RECORD_VALUE_ABBREV) 3864 llvm_unreachable("Unexpected abbrev ordering! 1"); 3865 } 3866 Stream.ExitBlock(); 3867 } 3868 3869 /// Write the module path strings, currently only used when generating 3870 /// a combined index file. 3871 void IndexBitcodeWriter::writeModStrings() { 3872 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3); 3873 3874 // TODO: See which abbrev sizes we actually need to emit 3875 3876 // 8-bit fixed-width MST_ENTRY strings. 3877 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3878 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3879 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3880 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3881 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 3882 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv)); 3883 3884 // 7-bit fixed width MST_ENTRY strings. 3885 Abbv = std::make_shared<BitCodeAbbrev>(); 3886 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3887 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3888 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3889 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 3890 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv)); 3891 3892 // 6-bit char6 MST_ENTRY strings. 3893 Abbv = std::make_shared<BitCodeAbbrev>(); 3894 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3895 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3896 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3897 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3898 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv)); 3899 3900 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY. 3901 Abbv = std::make_shared<BitCodeAbbrev>(); 3902 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH)); 3903 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3904 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3905 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3906 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3907 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3908 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv)); 3909 3910 SmallVector<unsigned, 64> Vals; 3911 forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) { 3912 StringRef Key = MPSE.getKey(); 3913 const auto &Hash = MPSE.getValue(); 3914 StringEncoding Bits = getStringEncoding(Key); 3915 unsigned AbbrevToUse = Abbrev8Bit; 3916 if (Bits == SE_Char6) 3917 AbbrevToUse = Abbrev6Bit; 3918 else if (Bits == SE_Fixed7) 3919 AbbrevToUse = Abbrev7Bit; 3920 3921 auto ModuleId = ModuleIdMap.size(); 3922 ModuleIdMap[Key] = ModuleId; 3923 Vals.push_back(ModuleId); 3924 Vals.append(Key.begin(), Key.end()); 3925 3926 // Emit the finished record. 3927 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse); 3928 3929 // Emit an optional hash for the module now 3930 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) { 3931 Vals.assign(Hash.begin(), Hash.end()); 3932 // Emit the hash record. 3933 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash); 3934 } 3935 3936 Vals.clear(); 3937 }); 3938 Stream.ExitBlock(); 3939 } 3940 3941 /// Write the function type metadata related records that need to appear before 3942 /// a function summary entry (whether per-module or combined). 3943 template <typename Fn> 3944 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream, 3945 FunctionSummary *FS, 3946 Fn GetValueID) { 3947 if (!FS->type_tests().empty()) 3948 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests()); 3949 3950 SmallVector<uint64_t, 64> Record; 3951 3952 auto WriteVFuncIdVec = [&](uint64_t Ty, 3953 ArrayRef<FunctionSummary::VFuncId> VFs) { 3954 if (VFs.empty()) 3955 return; 3956 Record.clear(); 3957 for (auto &VF : VFs) { 3958 Record.push_back(VF.GUID); 3959 Record.push_back(VF.Offset); 3960 } 3961 Stream.EmitRecord(Ty, Record); 3962 }; 3963 3964 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS, 3965 FS->type_test_assume_vcalls()); 3966 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS, 3967 FS->type_checked_load_vcalls()); 3968 3969 auto WriteConstVCallVec = [&](uint64_t Ty, 3970 ArrayRef<FunctionSummary::ConstVCall> VCs) { 3971 for (auto &VC : VCs) { 3972 Record.clear(); 3973 Record.push_back(VC.VFunc.GUID); 3974 Record.push_back(VC.VFunc.Offset); 3975 llvm::append_range(Record, VC.Args); 3976 Stream.EmitRecord(Ty, Record); 3977 } 3978 }; 3979 3980 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL, 3981 FS->type_test_assume_const_vcalls()); 3982 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL, 3983 FS->type_checked_load_const_vcalls()); 3984 3985 auto WriteRange = [&](ConstantRange Range) { 3986 Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth); 3987 assert(Range.getLower().getNumWords() == 1); 3988 assert(Range.getUpper().getNumWords() == 1); 3989 emitSignedInt64(Record, *Range.getLower().getRawData()); 3990 emitSignedInt64(Record, *Range.getUpper().getRawData()); 3991 }; 3992 3993 if (!FS->paramAccesses().empty()) { 3994 Record.clear(); 3995 for (auto &Arg : FS->paramAccesses()) { 3996 size_t UndoSize = Record.size(); 3997 Record.push_back(Arg.ParamNo); 3998 WriteRange(Arg.Use); 3999 Record.push_back(Arg.Calls.size()); 4000 for (auto &Call : Arg.Calls) { 4001 Record.push_back(Call.ParamNo); 4002 std::optional<unsigned> ValueID = GetValueID(Call.Callee); 4003 if (!ValueID) { 4004 // If ValueID is unknown we can't drop just this call, we must drop 4005 // entire parameter. 4006 Record.resize(UndoSize); 4007 break; 4008 } 4009 Record.push_back(*ValueID); 4010 WriteRange(Call.Offsets); 4011 } 4012 } 4013 if (!Record.empty()) 4014 Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record); 4015 } 4016 } 4017 4018 /// Collect type IDs from type tests used by function. 4019 static void 4020 getReferencedTypeIds(FunctionSummary *FS, 4021 std::set<GlobalValue::GUID> &ReferencedTypeIds) { 4022 if (!FS->type_tests().empty()) 4023 for (auto &TT : FS->type_tests()) 4024 ReferencedTypeIds.insert(TT); 4025 4026 auto GetReferencedTypesFromVFuncIdVec = 4027 [&](ArrayRef<FunctionSummary::VFuncId> VFs) { 4028 for (auto &VF : VFs) 4029 ReferencedTypeIds.insert(VF.GUID); 4030 }; 4031 4032 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls()); 4033 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls()); 4034 4035 auto GetReferencedTypesFromConstVCallVec = 4036 [&](ArrayRef<FunctionSummary::ConstVCall> VCs) { 4037 for (auto &VC : VCs) 4038 ReferencedTypeIds.insert(VC.VFunc.GUID); 4039 }; 4040 4041 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls()); 4042 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls()); 4043 } 4044 4045 static void writeWholeProgramDevirtResolutionByArg( 4046 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args, 4047 const WholeProgramDevirtResolution::ByArg &ByArg) { 4048 NameVals.push_back(args.size()); 4049 llvm::append_range(NameVals, args); 4050 4051 NameVals.push_back(ByArg.TheKind); 4052 NameVals.push_back(ByArg.Info); 4053 NameVals.push_back(ByArg.Byte); 4054 NameVals.push_back(ByArg.Bit); 4055 } 4056 4057 static void writeWholeProgramDevirtResolution( 4058 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder, 4059 uint64_t Id, const WholeProgramDevirtResolution &Wpd) { 4060 NameVals.push_back(Id); 4061 4062 NameVals.push_back(Wpd.TheKind); 4063 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName)); 4064 NameVals.push_back(Wpd.SingleImplName.size()); 4065 4066 NameVals.push_back(Wpd.ResByArg.size()); 4067 for (auto &A : Wpd.ResByArg) 4068 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second); 4069 } 4070 4071 static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals, 4072 StringTableBuilder &StrtabBuilder, 4073 const std::string &Id, 4074 const TypeIdSummary &Summary) { 4075 NameVals.push_back(StrtabBuilder.add(Id)); 4076 NameVals.push_back(Id.size()); 4077 4078 NameVals.push_back(Summary.TTRes.TheKind); 4079 NameVals.push_back(Summary.TTRes.SizeM1BitWidth); 4080 NameVals.push_back(Summary.TTRes.AlignLog2); 4081 NameVals.push_back(Summary.TTRes.SizeM1); 4082 NameVals.push_back(Summary.TTRes.BitMask); 4083 NameVals.push_back(Summary.TTRes.InlineBits); 4084 4085 for (auto &W : Summary.WPDRes) 4086 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first, 4087 W.second); 4088 } 4089 4090 static void writeTypeIdCompatibleVtableSummaryRecord( 4091 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder, 4092 const std::string &Id, const TypeIdCompatibleVtableInfo &Summary, 4093 ValueEnumerator &VE) { 4094 NameVals.push_back(StrtabBuilder.add(Id)); 4095 NameVals.push_back(Id.size()); 4096 4097 for (auto &P : Summary) { 4098 NameVals.push_back(P.AddressPointOffset); 4099 NameVals.push_back(VE.getValueID(P.VTableVI.getValue())); 4100 } 4101 } 4102 4103 static void writeFunctionHeapProfileRecords( 4104 BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev, 4105 unsigned AllocAbbrev, bool PerModule, 4106 std::function<unsigned(const ValueInfo &VI)> GetValueID, 4107 std::function<unsigned(unsigned)> GetStackIndex) { 4108 SmallVector<uint64_t> Record; 4109 4110 for (auto &CI : FS->callsites()) { 4111 Record.clear(); 4112 // Per module callsite clones should always have a single entry of 4113 // value 0. 4114 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0)); 4115 Record.push_back(GetValueID(CI.Callee)); 4116 if (!PerModule) { 4117 Record.push_back(CI.StackIdIndices.size()); 4118 Record.push_back(CI.Clones.size()); 4119 } 4120 for (auto Id : CI.StackIdIndices) 4121 Record.push_back(GetStackIndex(Id)); 4122 if (!PerModule) { 4123 for (auto V : CI.Clones) 4124 Record.push_back(V); 4125 } 4126 Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_CALLSITE_INFO 4127 : bitc::FS_COMBINED_CALLSITE_INFO, 4128 Record, CallsiteAbbrev); 4129 } 4130 4131 for (auto &AI : FS->allocs()) { 4132 Record.clear(); 4133 // Per module alloc versions should always have a single entry of 4134 // value 0. 4135 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0)); 4136 if (!PerModule) { 4137 Record.push_back(AI.MIBs.size()); 4138 Record.push_back(AI.Versions.size()); 4139 } 4140 for (auto &MIB : AI.MIBs) { 4141 Record.push_back((uint8_t)MIB.AllocType); 4142 Record.push_back(MIB.StackIdIndices.size()); 4143 for (auto Id : MIB.StackIdIndices) 4144 Record.push_back(GetStackIndex(Id)); 4145 } 4146 if (!PerModule) { 4147 for (auto V : AI.Versions) 4148 Record.push_back(V); 4149 } 4150 Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_ALLOC_INFO 4151 : bitc::FS_COMBINED_ALLOC_INFO, 4152 Record, AllocAbbrev); 4153 } 4154 } 4155 4156 // Helper to emit a single function summary record. 4157 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord( 4158 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary, 4159 unsigned ValueID, unsigned FSCallsRelBFAbbrev, 4160 unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev, 4161 unsigned AllocAbbrev, const Function &F) { 4162 NameVals.push_back(ValueID); 4163 4164 FunctionSummary *FS = cast<FunctionSummary>(Summary); 4165 4166 writeFunctionTypeMetadataRecords( 4167 Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> { 4168 return {VE.getValueID(VI.getValue())}; 4169 }); 4170 4171 writeFunctionHeapProfileRecords( 4172 Stream, FS, CallsiteAbbrev, AllocAbbrev, 4173 /*PerModule*/ true, 4174 /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); }, 4175 /*GetStackIndex*/ [&](unsigned I) { return I; }); 4176 4177 auto SpecialRefCnts = FS->specialRefCounts(); 4178 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags())); 4179 NameVals.push_back(FS->instCount()); 4180 NameVals.push_back(getEncodedFFlags(FS->fflags())); 4181 NameVals.push_back(FS->refs().size()); 4182 NameVals.push_back(SpecialRefCnts.first); // rorefcnt 4183 NameVals.push_back(SpecialRefCnts.second); // worefcnt 4184 4185 for (auto &RI : FS->refs()) 4186 NameVals.push_back(VE.getValueID(RI.getValue())); 4187 4188 const bool UseRelBFRecord = 4189 WriteRelBFToSummary && !F.hasProfileData() && 4190 ForceSummaryEdgesCold == FunctionSummary::FSHT_None; 4191 for (auto &ECI : FS->calls()) { 4192 NameVals.push_back(getValueId(ECI.first)); 4193 if (UseRelBFRecord) 4194 NameVals.push_back(getEncodedRelBFCallEdgeInfo(ECI.second)); 4195 else 4196 NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second)); 4197 } 4198 4199 unsigned FSAbbrev = 4200 (UseRelBFRecord ? FSCallsRelBFAbbrev : FSCallsProfileAbbrev); 4201 unsigned Code = 4202 (UseRelBFRecord ? bitc::FS_PERMODULE_RELBF : bitc::FS_PERMODULE_PROFILE); 4203 4204 // Emit the finished record. 4205 Stream.EmitRecord(Code, NameVals, FSAbbrev); 4206 NameVals.clear(); 4207 } 4208 4209 // Collect the global value references in the given variable's initializer, 4210 // and emit them in a summary record. 4211 void ModuleBitcodeWriterBase::writeModuleLevelReferences( 4212 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals, 4213 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) { 4214 auto VI = Index->getValueInfo(V.getGUID()); 4215 if (!VI || VI.getSummaryList().empty()) { 4216 // Only declarations should not have a summary (a declaration might however 4217 // have a summary if the def was in module level asm). 4218 assert(V.isDeclaration()); 4219 return; 4220 } 4221 auto *Summary = VI.getSummaryList()[0].get(); 4222 NameVals.push_back(VE.getValueID(&V)); 4223 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary); 4224 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags())); 4225 NameVals.push_back(getEncodedGVarFlags(VS->varflags())); 4226 4227 auto VTableFuncs = VS->vTableFuncs(); 4228 if (!VTableFuncs.empty()) 4229 NameVals.push_back(VS->refs().size()); 4230 4231 unsigned SizeBeforeRefs = NameVals.size(); 4232 for (auto &RI : VS->refs()) 4233 NameVals.push_back(VE.getValueID(RI.getValue())); 4234 // Sort the refs for determinism output, the vector returned by FS->refs() has 4235 // been initialized from a DenseSet. 4236 llvm::sort(drop_begin(NameVals, SizeBeforeRefs)); 4237 4238 if (VTableFuncs.empty()) 4239 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals, 4240 FSModRefsAbbrev); 4241 else { 4242 // VTableFuncs pairs should already be sorted by offset. 4243 for (auto &P : VTableFuncs) { 4244 NameVals.push_back(VE.getValueID(P.FuncVI.getValue())); 4245 NameVals.push_back(P.VTableOffset); 4246 } 4247 4248 Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals, 4249 FSModVTableRefsAbbrev); 4250 } 4251 NameVals.clear(); 4252 } 4253 4254 /// Emit the per-module summary section alongside the rest of 4255 /// the module's bitcode. 4256 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() { 4257 // By default we compile with ThinLTO if the module has a summary, but the 4258 // client can request full LTO with a module flag. 4259 bool IsThinLTO = true; 4260 if (auto *MD = 4261 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO"))) 4262 IsThinLTO = MD->getZExtValue(); 4263 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID 4264 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID, 4265 4); 4266 4267 Stream.EmitRecord( 4268 bitc::FS_VERSION, 4269 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion}); 4270 4271 // Write the index flags. 4272 uint64_t Flags = 0; 4273 // Bits 1-3 are set only in the combined index, skip them. 4274 if (Index->enableSplitLTOUnit()) 4275 Flags |= 0x8; 4276 if (Index->hasUnifiedLTO()) 4277 Flags |= 0x200; 4278 4279 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags}); 4280 4281 if (Index->begin() == Index->end()) { 4282 Stream.ExitBlock(); 4283 return; 4284 } 4285 4286 for (const auto &GVI : valueIds()) { 4287 Stream.EmitRecord(bitc::FS_VALUE_GUID, 4288 ArrayRef<uint64_t>{GVI.second, GVI.first}); 4289 } 4290 4291 if (!Index->stackIds().empty()) { 4292 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>(); 4293 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS)); 4294 // numids x stackid 4295 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4296 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4297 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv)); 4298 Stream.EmitRecord(bitc::FS_STACK_IDS, Index->stackIds(), StackIdAbbvId); 4299 } 4300 4301 // Abbrev for FS_PERMODULE_PROFILE. 4302 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4303 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE)); 4304 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4305 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags 4306 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 4307 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 4308 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 4309 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 4310 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 4311 // numrefs x valueid, n x (valueid, hotness+tailcall flags) 4312 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4313 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4314 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4315 4316 // Abbrev for FS_PERMODULE_RELBF. 4317 Abbv = std::make_shared<BitCodeAbbrev>(); 4318 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF)); 4319 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4320 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4321 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 4322 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 4323 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 4324 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 4325 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 4326 // numrefs x valueid, n x (valueid, rel_block_freq+tailcall]) 4327 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4328 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4329 unsigned FSCallsRelBFAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4330 4331 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS. 4332 Abbv = std::make_shared<BitCodeAbbrev>(); 4333 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS)); 4334 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4335 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4336 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 4337 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4338 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4339 4340 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS. 4341 Abbv = std::make_shared<BitCodeAbbrev>(); 4342 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS)); 4343 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4344 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4345 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 4346 // numrefs x valueid, n x (valueid , offset) 4347 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4348 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4349 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4350 4351 // Abbrev for FS_ALIAS. 4352 Abbv = std::make_shared<BitCodeAbbrev>(); 4353 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS)); 4354 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4355 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4356 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4357 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4358 4359 // Abbrev for FS_TYPE_ID_METADATA 4360 Abbv = std::make_shared<BitCodeAbbrev>(); 4361 Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA)); 4362 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index 4363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length 4364 // n x (valueid , offset) 4365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4367 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4368 4369 Abbv = std::make_shared<BitCodeAbbrev>(); 4370 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_CALLSITE_INFO)); 4371 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4372 // n x stackidindex 4373 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4374 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4375 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4376 4377 Abbv = std::make_shared<BitCodeAbbrev>(); 4378 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_ALLOC_INFO)); 4379 // n x (alloc type, numstackids, numstackids x stackidindex) 4380 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4381 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4382 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4383 4384 SmallVector<uint64_t, 64> NameVals; 4385 // Iterate over the list of functions instead of the Index to 4386 // ensure the ordering is stable. 4387 for (const Function &F : M) { 4388 // Summary emission does not support anonymous functions, they have to 4389 // renamed using the anonymous function renaming pass. 4390 if (!F.hasName()) 4391 report_fatal_error("Unexpected anonymous function when writing summary"); 4392 4393 ValueInfo VI = Index->getValueInfo(F.getGUID()); 4394 if (!VI || VI.getSummaryList().empty()) { 4395 // Only declarations should not have a summary (a declaration might 4396 // however have a summary if the def was in module level asm). 4397 assert(F.isDeclaration()); 4398 continue; 4399 } 4400 auto *Summary = VI.getSummaryList()[0].get(); 4401 writePerModuleFunctionSummaryRecord( 4402 NameVals, Summary, VE.getValueID(&F), FSCallsRelBFAbbrev, 4403 FSCallsProfileAbbrev, CallsiteAbbrev, AllocAbbrev, F); 4404 } 4405 4406 // Capture references from GlobalVariable initializers, which are outside 4407 // of a function scope. 4408 for (const GlobalVariable &G : M.globals()) 4409 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev, 4410 FSModVTableRefsAbbrev); 4411 4412 for (const GlobalAlias &A : M.aliases()) { 4413 auto *Aliasee = A.getAliaseeObject(); 4414 // Skip ifunc and nameless functions which don't have an entry in the 4415 // summary. 4416 if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee)) 4417 continue; 4418 auto AliasId = VE.getValueID(&A); 4419 auto AliaseeId = VE.getValueID(Aliasee); 4420 NameVals.push_back(AliasId); 4421 auto *Summary = Index->getGlobalValueSummary(A); 4422 AliasSummary *AS = cast<AliasSummary>(Summary); 4423 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags())); 4424 NameVals.push_back(AliaseeId); 4425 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev); 4426 NameVals.clear(); 4427 } 4428 4429 for (auto &S : Index->typeIdCompatibleVtableMap()) { 4430 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first, 4431 S.second, VE); 4432 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals, 4433 TypeIdCompatibleVtableAbbrev); 4434 NameVals.clear(); 4435 } 4436 4437 if (Index->getBlockCount()) 4438 Stream.EmitRecord(bitc::FS_BLOCK_COUNT, 4439 ArrayRef<uint64_t>{Index->getBlockCount()}); 4440 4441 Stream.ExitBlock(); 4442 } 4443 4444 /// Emit the combined summary section into the combined index file. 4445 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() { 4446 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4); 4447 Stream.EmitRecord( 4448 bitc::FS_VERSION, 4449 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion}); 4450 4451 // Write the index flags. 4452 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()}); 4453 4454 for (const auto &GVI : valueIds()) { 4455 Stream.EmitRecord(bitc::FS_VALUE_GUID, 4456 ArrayRef<uint64_t>{GVI.second, GVI.first}); 4457 } 4458 4459 if (!StackIdIndices.empty()) { 4460 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>(); 4461 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS)); 4462 // numids x stackid 4463 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4464 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4465 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv)); 4466 // Write the stack ids used by this index, which will be a subset of those in 4467 // the full index in the case of distributed indexes. 4468 std::vector<uint64_t> StackIds; 4469 for (auto &I : StackIdIndices) 4470 StackIds.push_back(Index.getStackIdAtIndex(I)); 4471 Stream.EmitRecord(bitc::FS_STACK_IDS, StackIds, StackIdAbbvId); 4472 } 4473 4474 // Abbrev for FS_COMBINED_PROFILE. 4475 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4476 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE)); 4477 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4478 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 4479 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4480 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 4481 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 4482 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount 4483 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 4484 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 4485 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 4486 // numrefs x valueid, n x (valueid, hotness+tailcall flags) 4487 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4488 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4489 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4490 4491 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS. 4492 Abbv = std::make_shared<BitCodeAbbrev>(); 4493 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS)); 4494 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4495 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 4496 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4497 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 4498 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4499 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4500 4501 // Abbrev for FS_COMBINED_ALIAS. 4502 Abbv = std::make_shared<BitCodeAbbrev>(); 4503 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS)); 4504 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4505 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 4506 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4507 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4508 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4509 4510 Abbv = std::make_shared<BitCodeAbbrev>(); 4511 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_CALLSITE_INFO)); 4512 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4513 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices 4514 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver 4515 // numstackindices x stackidindex, numver x version 4516 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4517 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4518 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4519 4520 Abbv = std::make_shared<BitCodeAbbrev>(); 4521 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALLOC_INFO)); 4522 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib 4523 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver 4524 // nummib x (alloc type, numstackids, numstackids x stackidindex), 4525 // numver x version 4526 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4527 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4528 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4529 4530 // The aliases are emitted as a post-pass, and will point to the value 4531 // id of the aliasee. Save them in a vector for post-processing. 4532 SmallVector<AliasSummary *, 64> Aliases; 4533 4534 // Save the value id for each summary for alias emission. 4535 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap; 4536 4537 SmallVector<uint64_t, 64> NameVals; 4538 4539 // Set that will be populated during call to writeFunctionTypeMetadataRecords 4540 // with the type ids referenced by this index file. 4541 std::set<GlobalValue::GUID> ReferencedTypeIds; 4542 4543 // For local linkage, we also emit the original name separately 4544 // immediately after the record. 4545 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) { 4546 // We don't need to emit the original name if we are writing the index for 4547 // distributed backends (in which case ModuleToSummariesForIndex is 4548 // non-null). The original name is only needed during the thin link, since 4549 // for SamplePGO the indirect call targets for local functions have 4550 // have the original name annotated in profile. 4551 // Continue to emit it when writing out the entire combined index, which is 4552 // used in testing the thin link via llvm-lto. 4553 if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage())) 4554 return; 4555 NameVals.push_back(S.getOriginalName()); 4556 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals); 4557 NameVals.clear(); 4558 }; 4559 4560 std::set<GlobalValue::GUID> DefOrUseGUIDs; 4561 forEachSummary([&](GVInfo I, bool IsAliasee) { 4562 GlobalValueSummary *S = I.second; 4563 assert(S); 4564 DefOrUseGUIDs.insert(I.first); 4565 for (const ValueInfo &VI : S->refs()) 4566 DefOrUseGUIDs.insert(VI.getGUID()); 4567 4568 auto ValueId = getValueId(I.first); 4569 assert(ValueId); 4570 SummaryToValueIdMap[S] = *ValueId; 4571 4572 // If this is invoked for an aliasee, we want to record the above 4573 // mapping, but then not emit a summary entry (if the aliasee is 4574 // to be imported, we will invoke this separately with IsAliasee=false). 4575 if (IsAliasee) 4576 return; 4577 4578 if (auto *AS = dyn_cast<AliasSummary>(S)) { 4579 // Will process aliases as a post-pass because the reader wants all 4580 // global to be loaded first. 4581 Aliases.push_back(AS); 4582 return; 4583 } 4584 4585 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) { 4586 NameVals.push_back(*ValueId); 4587 assert(ModuleIdMap.count(VS->modulePath())); 4588 NameVals.push_back(ModuleIdMap[VS->modulePath()]); 4589 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags())); 4590 NameVals.push_back(getEncodedGVarFlags(VS->varflags())); 4591 for (auto &RI : VS->refs()) { 4592 auto RefValueId = getValueId(RI.getGUID()); 4593 if (!RefValueId) 4594 continue; 4595 NameVals.push_back(*RefValueId); 4596 } 4597 4598 // Emit the finished record. 4599 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals, 4600 FSModRefsAbbrev); 4601 NameVals.clear(); 4602 MaybeEmitOriginalName(*S); 4603 return; 4604 } 4605 4606 auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> { 4607 if (!VI) 4608 return std::nullopt; 4609 return getValueId(VI.getGUID()); 4610 }; 4611 4612 auto *FS = cast<FunctionSummary>(S); 4613 writeFunctionTypeMetadataRecords(Stream, FS, GetValueId); 4614 getReferencedTypeIds(FS, ReferencedTypeIds); 4615 4616 writeFunctionHeapProfileRecords( 4617 Stream, FS, CallsiteAbbrev, AllocAbbrev, 4618 /*PerModule*/ false, 4619 /*GetValueId*/ [&](const ValueInfo &VI) -> unsigned { 4620 std::optional<unsigned> ValueID = GetValueId(VI); 4621 // This can happen in shared index files for distributed ThinLTO if 4622 // the callee function summary is not included. Record 0 which we 4623 // will have to deal with conservatively when doing any kind of 4624 // validation in the ThinLTO backends. 4625 if (!ValueID) 4626 return 0; 4627 return *ValueID; 4628 }, 4629 /*GetStackIndex*/ [&](unsigned I) { 4630 // Get the corresponding index into the list of StackIdIndices 4631 // actually being written for this combined index (which may be a 4632 // subset in the case of distributed indexes). 4633 auto Lower = llvm::lower_bound(StackIdIndices, I); 4634 return std::distance(StackIdIndices.begin(), Lower); 4635 }); 4636 4637 NameVals.push_back(*ValueId); 4638 assert(ModuleIdMap.count(FS->modulePath())); 4639 NameVals.push_back(ModuleIdMap[FS->modulePath()]); 4640 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags())); 4641 NameVals.push_back(FS->instCount()); 4642 NameVals.push_back(getEncodedFFlags(FS->fflags())); 4643 NameVals.push_back(FS->entryCount()); 4644 4645 // Fill in below 4646 NameVals.push_back(0); // numrefs 4647 NameVals.push_back(0); // rorefcnt 4648 NameVals.push_back(0); // worefcnt 4649 4650 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0; 4651 for (auto &RI : FS->refs()) { 4652 auto RefValueId = getValueId(RI.getGUID()); 4653 if (!RefValueId) 4654 continue; 4655 NameVals.push_back(*RefValueId); 4656 if (RI.isReadOnly()) 4657 RORefCnt++; 4658 else if (RI.isWriteOnly()) 4659 WORefCnt++; 4660 Count++; 4661 } 4662 NameVals[6] = Count; 4663 NameVals[7] = RORefCnt; 4664 NameVals[8] = WORefCnt; 4665 4666 for (auto &EI : FS->calls()) { 4667 // If this GUID doesn't have a value id, it doesn't have a function 4668 // summary and we don't need to record any calls to it. 4669 std::optional<unsigned> CallValueId = GetValueId(EI.first); 4670 if (!CallValueId) 4671 continue; 4672 NameVals.push_back(*CallValueId); 4673 NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second)); 4674 } 4675 4676 // Emit the finished record. 4677 Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals, 4678 FSCallsProfileAbbrev); 4679 NameVals.clear(); 4680 MaybeEmitOriginalName(*S); 4681 }); 4682 4683 for (auto *AS : Aliases) { 4684 auto AliasValueId = SummaryToValueIdMap[AS]; 4685 assert(AliasValueId); 4686 NameVals.push_back(AliasValueId); 4687 assert(ModuleIdMap.count(AS->modulePath())); 4688 NameVals.push_back(ModuleIdMap[AS->modulePath()]); 4689 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags())); 4690 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()]; 4691 assert(AliaseeValueId); 4692 NameVals.push_back(AliaseeValueId); 4693 4694 // Emit the finished record. 4695 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev); 4696 NameVals.clear(); 4697 MaybeEmitOriginalName(*AS); 4698 4699 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee())) 4700 getReferencedTypeIds(FS, ReferencedTypeIds); 4701 } 4702 4703 if (!Index.cfiFunctionDefs().empty()) { 4704 for (auto &S : Index.cfiFunctionDefs()) { 4705 if (DefOrUseGUIDs.count( 4706 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) { 4707 NameVals.push_back(StrtabBuilder.add(S)); 4708 NameVals.push_back(S.size()); 4709 } 4710 } 4711 if (!NameVals.empty()) { 4712 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals); 4713 NameVals.clear(); 4714 } 4715 } 4716 4717 if (!Index.cfiFunctionDecls().empty()) { 4718 for (auto &S : Index.cfiFunctionDecls()) { 4719 if (DefOrUseGUIDs.count( 4720 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) { 4721 NameVals.push_back(StrtabBuilder.add(S)); 4722 NameVals.push_back(S.size()); 4723 } 4724 } 4725 if (!NameVals.empty()) { 4726 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals); 4727 NameVals.clear(); 4728 } 4729 } 4730 4731 // Walk the GUIDs that were referenced, and write the 4732 // corresponding type id records. 4733 for (auto &T : ReferencedTypeIds) { 4734 auto TidIter = Index.typeIds().equal_range(T); 4735 for (auto It = TidIter.first; It != TidIter.second; ++It) { 4736 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first, 4737 It->second.second); 4738 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals); 4739 NameVals.clear(); 4740 } 4741 } 4742 4743 if (Index.getBlockCount()) 4744 Stream.EmitRecord(bitc::FS_BLOCK_COUNT, 4745 ArrayRef<uint64_t>{Index.getBlockCount()}); 4746 4747 Stream.ExitBlock(); 4748 } 4749 4750 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the 4751 /// current llvm version, and a record for the epoch number. 4752 static void writeIdentificationBlock(BitstreamWriter &Stream) { 4753 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5); 4754 4755 // Write the "user readable" string identifying the bitcode producer 4756 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4757 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING)); 4758 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4759 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 4760 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4761 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING, 4762 "LLVM" LLVM_VERSION_STRING, StringAbbrev); 4763 4764 // Write the epoch version 4765 Abbv = std::make_shared<BitCodeAbbrev>(); 4766 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH)); 4767 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 4768 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4769 constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}}; 4770 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev); 4771 Stream.ExitBlock(); 4772 } 4773 4774 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) { 4775 // Emit the module's hash. 4776 // MODULE_CODE_HASH: [5*i32] 4777 if (GenerateHash) { 4778 uint32_t Vals[5]; 4779 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos], 4780 Buffer.size() - BlockStartPos)); 4781 std::array<uint8_t, 20> Hash = Hasher.result(); 4782 for (int Pos = 0; Pos < 20; Pos += 4) { 4783 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos); 4784 } 4785 4786 // Emit the finished record. 4787 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals); 4788 4789 if (ModHash) 4790 // Save the written hash value. 4791 llvm::copy(Vals, std::begin(*ModHash)); 4792 } 4793 } 4794 4795 void ModuleBitcodeWriter::write() { 4796 writeIdentificationBlock(Stream); 4797 4798 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 4799 size_t BlockStartPos = Buffer.size(); 4800 4801 writeModuleVersion(); 4802 4803 // Emit blockinfo, which defines the standard abbreviations etc. 4804 writeBlockInfo(); 4805 4806 // Emit information describing all of the types in the module. 4807 writeTypeTable(); 4808 4809 // Emit information about attribute groups. 4810 writeAttributeGroupTable(); 4811 4812 // Emit information about parameter attributes. 4813 writeAttributeTable(); 4814 4815 writeComdats(); 4816 4817 // Emit top-level description of module, including target triple, inline asm, 4818 // descriptors for global variables, and function prototype info. 4819 writeModuleInfo(); 4820 4821 // Emit constants. 4822 writeModuleConstants(); 4823 4824 // Emit metadata kind names. 4825 writeModuleMetadataKinds(); 4826 4827 // Emit metadata. 4828 writeModuleMetadata(); 4829 4830 // Emit module-level use-lists. 4831 if (VE.shouldPreserveUseListOrder()) 4832 writeUseListBlock(nullptr); 4833 4834 writeOperandBundleTags(); 4835 writeSyncScopeNames(); 4836 4837 // Emit function bodies. 4838 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex; 4839 for (const Function &F : M) 4840 if (!F.isDeclaration()) 4841 writeFunction(F, FunctionToBitcodeIndex); 4842 4843 // Need to write after the above call to WriteFunction which populates 4844 // the summary information in the index. 4845 if (Index) 4846 writePerModuleGlobalValueSummary(); 4847 4848 writeGlobalValueSymbolTable(FunctionToBitcodeIndex); 4849 4850 writeModuleHash(BlockStartPos); 4851 4852 Stream.ExitBlock(); 4853 } 4854 4855 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer, 4856 uint32_t &Position) { 4857 support::endian::write32le(&Buffer[Position], Value); 4858 Position += 4; 4859 } 4860 4861 /// If generating a bc file on darwin, we have to emit a 4862 /// header and trailer to make it compatible with the system archiver. To do 4863 /// this we emit the following header, and then emit a trailer that pads the 4864 /// file out to be a multiple of 16 bytes. 4865 /// 4866 /// struct bc_header { 4867 /// uint32_t Magic; // 0x0B17C0DE 4868 /// uint32_t Version; // Version, currently always 0. 4869 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file. 4870 /// uint32_t BitcodeSize; // Size of traditional bitcode file. 4871 /// uint32_t CPUType; // CPU specifier. 4872 /// ... potentially more later ... 4873 /// }; 4874 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer, 4875 const Triple &TT) { 4876 unsigned CPUType = ~0U; 4877 4878 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*, 4879 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic 4880 // number from /usr/include/mach/machine.h. It is ok to reproduce the 4881 // specific constants here because they are implicitly part of the Darwin ABI. 4882 enum { 4883 DARWIN_CPU_ARCH_ABI64 = 0x01000000, 4884 DARWIN_CPU_TYPE_X86 = 7, 4885 DARWIN_CPU_TYPE_ARM = 12, 4886 DARWIN_CPU_TYPE_POWERPC = 18 4887 }; 4888 4889 Triple::ArchType Arch = TT.getArch(); 4890 if (Arch == Triple::x86_64) 4891 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64; 4892 else if (Arch == Triple::x86) 4893 CPUType = DARWIN_CPU_TYPE_X86; 4894 else if (Arch == Triple::ppc) 4895 CPUType = DARWIN_CPU_TYPE_POWERPC; 4896 else if (Arch == Triple::ppc64) 4897 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64; 4898 else if (Arch == Triple::arm || Arch == Triple::thumb) 4899 CPUType = DARWIN_CPU_TYPE_ARM; 4900 4901 // Traditional Bitcode starts after header. 4902 assert(Buffer.size() >= BWH_HeaderSize && 4903 "Expected header size to be reserved"); 4904 unsigned BCOffset = BWH_HeaderSize; 4905 unsigned BCSize = Buffer.size() - BWH_HeaderSize; 4906 4907 // Write the magic and version. 4908 unsigned Position = 0; 4909 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position); 4910 writeInt32ToBuffer(0, Buffer, Position); // Version. 4911 writeInt32ToBuffer(BCOffset, Buffer, Position); 4912 writeInt32ToBuffer(BCSize, Buffer, Position); 4913 writeInt32ToBuffer(CPUType, Buffer, Position); 4914 4915 // If the file is not a multiple of 16 bytes, insert dummy padding. 4916 while (Buffer.size() & 15) 4917 Buffer.push_back(0); 4918 } 4919 4920 /// Helper to write the header common to all bitcode files. 4921 static void writeBitcodeHeader(BitstreamWriter &Stream) { 4922 // Emit the file header. 4923 Stream.Emit((unsigned)'B', 8); 4924 Stream.Emit((unsigned)'C', 8); 4925 Stream.Emit(0x0, 4); 4926 Stream.Emit(0xC, 4); 4927 Stream.Emit(0xE, 4); 4928 Stream.Emit(0xD, 4); 4929 } 4930 4931 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer, raw_fd_stream *FS) 4932 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer, FS, FlushThreshold)) { 4933 writeBitcodeHeader(*Stream); 4934 } 4935 4936 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); } 4937 4938 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) { 4939 Stream->EnterSubblock(Block, 3); 4940 4941 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4942 Abbv->Add(BitCodeAbbrevOp(Record)); 4943 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 4944 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv)); 4945 4946 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob); 4947 4948 Stream->ExitBlock(); 4949 } 4950 4951 void BitcodeWriter::writeSymtab() { 4952 assert(!WroteStrtab && !WroteSymtab); 4953 4954 // If any module has module-level inline asm, we will require a registered asm 4955 // parser for the target so that we can create an accurate symbol table for 4956 // the module. 4957 for (Module *M : Mods) { 4958 if (M->getModuleInlineAsm().empty()) 4959 continue; 4960 4961 std::string Err; 4962 const Triple TT(M->getTargetTriple()); 4963 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err); 4964 if (!T || !T->hasMCAsmParser()) 4965 return; 4966 } 4967 4968 WroteSymtab = true; 4969 SmallVector<char, 0> Symtab; 4970 // The irsymtab::build function may be unable to create a symbol table if the 4971 // module is malformed (e.g. it contains an invalid alias). Writing a symbol 4972 // table is not required for correctness, but we still want to be able to 4973 // write malformed modules to bitcode files, so swallow the error. 4974 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) { 4975 consumeError(std::move(E)); 4976 return; 4977 } 4978 4979 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB, 4980 {Symtab.data(), Symtab.size()}); 4981 } 4982 4983 void BitcodeWriter::writeStrtab() { 4984 assert(!WroteStrtab); 4985 4986 std::vector<char> Strtab; 4987 StrtabBuilder.finalizeInOrder(); 4988 Strtab.resize(StrtabBuilder.getSize()); 4989 StrtabBuilder.write((uint8_t *)Strtab.data()); 4990 4991 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, 4992 {Strtab.data(), Strtab.size()}); 4993 4994 WroteStrtab = true; 4995 } 4996 4997 void BitcodeWriter::copyStrtab(StringRef Strtab) { 4998 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab); 4999 WroteStrtab = true; 5000 } 5001 5002 void BitcodeWriter::writeModule(const Module &M, 5003 bool ShouldPreserveUseListOrder, 5004 const ModuleSummaryIndex *Index, 5005 bool GenerateHash, ModuleHash *ModHash) { 5006 assert(!WroteStrtab); 5007 5008 // The Mods vector is used by irsymtab::build, which requires non-const 5009 // Modules in case it needs to materialize metadata. But the bitcode writer 5010 // requires that the module is materialized, so we can cast to non-const here, 5011 // after checking that it is in fact materialized. 5012 assert(M.isMaterialized()); 5013 Mods.push_back(const_cast<Module *>(&M)); 5014 5015 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream, 5016 ShouldPreserveUseListOrder, Index, 5017 GenerateHash, ModHash); 5018 ModuleWriter.write(); 5019 } 5020 5021 void BitcodeWriter::writeIndex( 5022 const ModuleSummaryIndex *Index, 5023 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) { 5024 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, 5025 ModuleToSummariesForIndex); 5026 IndexWriter.write(); 5027 } 5028 5029 /// Write the specified module to the specified output stream. 5030 void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out, 5031 bool ShouldPreserveUseListOrder, 5032 const ModuleSummaryIndex *Index, 5033 bool GenerateHash, ModuleHash *ModHash) { 5034 SmallVector<char, 0> Buffer; 5035 Buffer.reserve(256*1024); 5036 5037 // If this is darwin or another generic macho target, reserve space for the 5038 // header. 5039 Triple TT(M.getTargetTriple()); 5040 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 5041 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0); 5042 5043 BitcodeWriter Writer(Buffer, dyn_cast<raw_fd_stream>(&Out)); 5044 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash, 5045 ModHash); 5046 Writer.writeSymtab(); 5047 Writer.writeStrtab(); 5048 5049 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 5050 emitDarwinBCHeaderAndTrailer(Buffer, TT); 5051 5052 // Write the generated bitstream to "Out". 5053 if (!Buffer.empty()) 5054 Out.write((char *)&Buffer.front(), Buffer.size()); 5055 } 5056 5057 void IndexBitcodeWriter::write() { 5058 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 5059 5060 writeModuleVersion(); 5061 5062 // Write the module paths in the combined index. 5063 writeModStrings(); 5064 5065 // Write the summary combined index records. 5066 writeCombinedGlobalValueSummary(); 5067 5068 Stream.ExitBlock(); 5069 } 5070 5071 // Write the specified module summary index to the given raw output stream, 5072 // where it will be written in a new bitcode block. This is used when 5073 // writing the combined index file for ThinLTO. When writing a subset of the 5074 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map. 5075 void llvm::writeIndexToFile( 5076 const ModuleSummaryIndex &Index, raw_ostream &Out, 5077 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) { 5078 SmallVector<char, 0> Buffer; 5079 Buffer.reserve(256 * 1024); 5080 5081 BitcodeWriter Writer(Buffer); 5082 Writer.writeIndex(&Index, ModuleToSummariesForIndex); 5083 Writer.writeStrtab(); 5084 5085 Out.write((char *)&Buffer.front(), Buffer.size()); 5086 } 5087 5088 namespace { 5089 5090 /// Class to manage the bitcode writing for a thin link bitcode file. 5091 class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase { 5092 /// ModHash is for use in ThinLTO incremental build, generated while writing 5093 /// the module bitcode file. 5094 const ModuleHash *ModHash; 5095 5096 public: 5097 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder, 5098 BitstreamWriter &Stream, 5099 const ModuleSummaryIndex &Index, 5100 const ModuleHash &ModHash) 5101 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream, 5102 /*ShouldPreserveUseListOrder=*/false, &Index), 5103 ModHash(&ModHash) {} 5104 5105 void write(); 5106 5107 private: 5108 void writeSimplifiedModuleInfo(); 5109 }; 5110 5111 } // end anonymous namespace 5112 5113 // This function writes a simpilified module info for thin link bitcode file. 5114 // It only contains the source file name along with the name(the offset and 5115 // size in strtab) and linkage for global values. For the global value info 5116 // entry, in order to keep linkage at offset 5, there are three zeros used 5117 // as padding. 5118 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() { 5119 SmallVector<unsigned, 64> Vals; 5120 // Emit the module's source file name. 5121 { 5122 StringEncoding Bits = getStringEncoding(M.getSourceFileName()); 5123 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8); 5124 if (Bits == SE_Char6) 5125 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6); 5126 else if (Bits == SE_Fixed7) 5127 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7); 5128 5129 // MODULE_CODE_SOURCE_FILENAME: [namechar x N] 5130 auto Abbv = std::make_shared<BitCodeAbbrev>(); 5131 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME)); 5132 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 5133 Abbv->Add(AbbrevOpToUse); 5134 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 5135 5136 for (const auto P : M.getSourceFileName()) 5137 Vals.push_back((unsigned char)P); 5138 5139 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev); 5140 Vals.clear(); 5141 } 5142 5143 // Emit the global variable information. 5144 for (const GlobalVariable &GV : M.globals()) { 5145 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage] 5146 Vals.push_back(StrtabBuilder.add(GV.getName())); 5147 Vals.push_back(GV.getName().size()); 5148 Vals.push_back(0); 5149 Vals.push_back(0); 5150 Vals.push_back(0); 5151 Vals.push_back(getEncodedLinkage(GV)); 5152 5153 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals); 5154 Vals.clear(); 5155 } 5156 5157 // Emit the function proto information. 5158 for (const Function &F : M) { 5159 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage] 5160 Vals.push_back(StrtabBuilder.add(F.getName())); 5161 Vals.push_back(F.getName().size()); 5162 Vals.push_back(0); 5163 Vals.push_back(0); 5164 Vals.push_back(0); 5165 Vals.push_back(getEncodedLinkage(F)); 5166 5167 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals); 5168 Vals.clear(); 5169 } 5170 5171 // Emit the alias information. 5172 for (const GlobalAlias &A : M.aliases()) { 5173 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage] 5174 Vals.push_back(StrtabBuilder.add(A.getName())); 5175 Vals.push_back(A.getName().size()); 5176 Vals.push_back(0); 5177 Vals.push_back(0); 5178 Vals.push_back(0); 5179 Vals.push_back(getEncodedLinkage(A)); 5180 5181 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals); 5182 Vals.clear(); 5183 } 5184 5185 // Emit the ifunc information. 5186 for (const GlobalIFunc &I : M.ifuncs()) { 5187 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage] 5188 Vals.push_back(StrtabBuilder.add(I.getName())); 5189 Vals.push_back(I.getName().size()); 5190 Vals.push_back(0); 5191 Vals.push_back(0); 5192 Vals.push_back(0); 5193 Vals.push_back(getEncodedLinkage(I)); 5194 5195 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals); 5196 Vals.clear(); 5197 } 5198 } 5199 5200 void ThinLinkBitcodeWriter::write() { 5201 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 5202 5203 writeModuleVersion(); 5204 5205 writeSimplifiedModuleInfo(); 5206 5207 writePerModuleGlobalValueSummary(); 5208 5209 // Write module hash. 5210 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash)); 5211 5212 Stream.ExitBlock(); 5213 } 5214 5215 void BitcodeWriter::writeThinLinkBitcode(const Module &M, 5216 const ModuleSummaryIndex &Index, 5217 const ModuleHash &ModHash) { 5218 assert(!WroteStrtab); 5219 5220 // The Mods vector is used by irsymtab::build, which requires non-const 5221 // Modules in case it needs to materialize metadata. But the bitcode writer 5222 // requires that the module is materialized, so we can cast to non-const here, 5223 // after checking that it is in fact materialized. 5224 assert(M.isMaterialized()); 5225 Mods.push_back(const_cast<Module *>(&M)); 5226 5227 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index, 5228 ModHash); 5229 ThinLinkWriter.write(); 5230 } 5231 5232 // Write the specified thin link bitcode file to the given raw output stream, 5233 // where it will be written in a new bitcode block. This is used when 5234 // writing the per-module index file for ThinLTO. 5235 void llvm::writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, 5236 const ModuleSummaryIndex &Index, 5237 const ModuleHash &ModHash) { 5238 SmallVector<char, 0> Buffer; 5239 Buffer.reserve(256 * 1024); 5240 5241 BitcodeWriter Writer(Buffer); 5242 Writer.writeThinLinkBitcode(M, Index, ModHash); 5243 Writer.writeSymtab(); 5244 Writer.writeStrtab(); 5245 5246 Out.write((char *)&Buffer.front(), Buffer.size()); 5247 } 5248 5249 static const char *getSectionNameForBitcode(const Triple &T) { 5250 switch (T.getObjectFormat()) { 5251 case Triple::MachO: 5252 return "__LLVM,__bitcode"; 5253 case Triple::COFF: 5254 case Triple::ELF: 5255 case Triple::Wasm: 5256 case Triple::UnknownObjectFormat: 5257 return ".llvmbc"; 5258 case Triple::GOFF: 5259 llvm_unreachable("GOFF is not yet implemented"); 5260 break; 5261 case Triple::SPIRV: 5262 llvm_unreachable("SPIRV is not yet implemented"); 5263 break; 5264 case Triple::XCOFF: 5265 llvm_unreachable("XCOFF is not yet implemented"); 5266 break; 5267 case Triple::DXContainer: 5268 llvm_unreachable("DXContainer is not yet implemented"); 5269 break; 5270 } 5271 llvm_unreachable("Unimplemented ObjectFormatType"); 5272 } 5273 5274 static const char *getSectionNameForCommandline(const Triple &T) { 5275 switch (T.getObjectFormat()) { 5276 case Triple::MachO: 5277 return "__LLVM,__cmdline"; 5278 case Triple::COFF: 5279 case Triple::ELF: 5280 case Triple::Wasm: 5281 case Triple::UnknownObjectFormat: 5282 return ".llvmcmd"; 5283 case Triple::GOFF: 5284 llvm_unreachable("GOFF is not yet implemented"); 5285 break; 5286 case Triple::SPIRV: 5287 llvm_unreachable("SPIRV is not yet implemented"); 5288 break; 5289 case Triple::XCOFF: 5290 llvm_unreachable("XCOFF is not yet implemented"); 5291 break; 5292 case Triple::DXContainer: 5293 llvm_unreachable("DXC is not yet implemented"); 5294 break; 5295 } 5296 llvm_unreachable("Unimplemented ObjectFormatType"); 5297 } 5298 5299 void llvm::embedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf, 5300 bool EmbedBitcode, bool EmbedCmdline, 5301 const std::vector<uint8_t> &CmdArgs) { 5302 // Save llvm.compiler.used and remove it. 5303 SmallVector<Constant *, 2> UsedArray; 5304 SmallVector<GlobalValue *, 4> UsedGlobals; 5305 Type *UsedElementType = PointerType::getUnqual(M.getContext()); 5306 GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true); 5307 for (auto *GV : UsedGlobals) { 5308 if (GV->getName() != "llvm.embedded.module" && 5309 GV->getName() != "llvm.cmdline") 5310 UsedArray.push_back( 5311 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 5312 } 5313 if (Used) 5314 Used->eraseFromParent(); 5315 5316 // Embed the bitcode for the llvm module. 5317 std::string Data; 5318 ArrayRef<uint8_t> ModuleData; 5319 Triple T(M.getTargetTriple()); 5320 5321 if (EmbedBitcode) { 5322 if (Buf.getBufferSize() == 0 || 5323 !isBitcode((const unsigned char *)Buf.getBufferStart(), 5324 (const unsigned char *)Buf.getBufferEnd())) { 5325 // If the input is LLVM Assembly, bitcode is produced by serializing 5326 // the module. Use-lists order need to be preserved in this case. 5327 llvm::raw_string_ostream OS(Data); 5328 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true); 5329 ModuleData = 5330 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size()); 5331 } else 5332 // If the input is LLVM bitcode, write the input byte stream directly. 5333 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(), 5334 Buf.getBufferSize()); 5335 } 5336 llvm::Constant *ModuleConstant = 5337 llvm::ConstantDataArray::get(M.getContext(), ModuleData); 5338 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 5339 M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage, 5340 ModuleConstant); 5341 GV->setSection(getSectionNameForBitcode(T)); 5342 // Set alignment to 1 to prevent padding between two contributions from input 5343 // sections after linking. 5344 GV->setAlignment(Align(1)); 5345 UsedArray.push_back( 5346 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 5347 if (llvm::GlobalVariable *Old = 5348 M.getGlobalVariable("llvm.embedded.module", true)) { 5349 assert(Old->hasZeroLiveUses() && 5350 "llvm.embedded.module can only be used once in llvm.compiler.used"); 5351 GV->takeName(Old); 5352 Old->eraseFromParent(); 5353 } else { 5354 GV->setName("llvm.embedded.module"); 5355 } 5356 5357 // Skip if only bitcode needs to be embedded. 5358 if (EmbedCmdline) { 5359 // Embed command-line options. 5360 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()), 5361 CmdArgs.size()); 5362 llvm::Constant *CmdConstant = 5363 llvm::ConstantDataArray::get(M.getContext(), CmdData); 5364 GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true, 5365 llvm::GlobalValue::PrivateLinkage, 5366 CmdConstant); 5367 GV->setSection(getSectionNameForCommandline(T)); 5368 GV->setAlignment(Align(1)); 5369 UsedArray.push_back( 5370 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 5371 if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) { 5372 assert(Old->hasZeroLiveUses() && 5373 "llvm.cmdline can only be used once in llvm.compiler.used"); 5374 GV->takeName(Old); 5375 Old->eraseFromParent(); 5376 } else { 5377 GV->setName("llvm.cmdline"); 5378 } 5379 } 5380 5381 if (UsedArray.empty()) 5382 return; 5383 5384 // Recreate llvm.compiler.used. 5385 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size()); 5386 auto *NewUsed = new GlobalVariable( 5387 M, ATy, false, llvm::GlobalValue::AppendingLinkage, 5388 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used"); 5389 NewUsed->setSection("llvm.metadata"); 5390 } 5391