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