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