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