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