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