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