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