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