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