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