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