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