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