1 //===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Bitcode writer implementation. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Bitcode/BitcodeWriter.h" 14 #include "ValueEnumerator.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/None.h" 20 #include "llvm/ADT/Optional.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/SmallString.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/StringMap.h" 25 #include "llvm/ADT/StringRef.h" 26 #include "llvm/ADT/Triple.h" 27 #include "llvm/Bitcode/BitcodeCommon.h" 28 #include "llvm/Bitcode/BitcodeReader.h" 29 #include "llvm/Bitcode/LLVMBitCodes.h" 30 #include "llvm/Bitstream/BitCodes.h" 31 #include "llvm/Bitstream/BitstreamWriter.h" 32 #include "llvm/Config/llvm-config.h" 33 #include "llvm/IR/Attributes.h" 34 #include "llvm/IR/BasicBlock.h" 35 #include "llvm/IR/Comdat.h" 36 #include "llvm/IR/Constant.h" 37 #include "llvm/IR/Constants.h" 38 #include "llvm/IR/DebugInfoMetadata.h" 39 #include "llvm/IR/DebugLoc.h" 40 #include "llvm/IR/DerivedTypes.h" 41 #include "llvm/IR/Function.h" 42 #include "llvm/IR/GlobalAlias.h" 43 #include "llvm/IR/GlobalIFunc.h" 44 #include "llvm/IR/GlobalObject.h" 45 #include "llvm/IR/GlobalValue.h" 46 #include "llvm/IR/GlobalVariable.h" 47 #include "llvm/IR/InlineAsm.h" 48 #include "llvm/IR/InstrTypes.h" 49 #include "llvm/IR/Instruction.h" 50 #include "llvm/IR/Instructions.h" 51 #include "llvm/IR/LLVMContext.h" 52 #include "llvm/IR/Metadata.h" 53 #include "llvm/IR/Module.h" 54 #include "llvm/IR/ModuleSummaryIndex.h" 55 #include "llvm/IR/Operator.h" 56 #include "llvm/IR/Type.h" 57 #include "llvm/IR/UseListOrder.h" 58 #include "llvm/IR/Value.h" 59 #include "llvm/IR/ValueSymbolTable.h" 60 #include "llvm/MC/StringTableBuilder.h" 61 #include "llvm/Object/IRSymtab.h" 62 #include "llvm/Support/AtomicOrdering.h" 63 #include "llvm/Support/Casting.h" 64 #include "llvm/Support/CommandLine.h" 65 #include "llvm/Support/Endian.h" 66 #include "llvm/Support/Error.h" 67 #include "llvm/Support/ErrorHandling.h" 68 #include "llvm/Support/MathExtras.h" 69 #include "llvm/Support/SHA1.h" 70 #include "llvm/Support/TargetRegistry.h" 71 #include "llvm/Support/raw_ostream.h" 72 #include <algorithm> 73 #include <cassert> 74 #include <cstddef> 75 #include <cstdint> 76 #include <iterator> 77 #include <map> 78 #include <memory> 79 #include <string> 80 #include <utility> 81 #include <vector> 82 83 using namespace llvm; 84 85 static cl::opt<unsigned> 86 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25), 87 cl::desc("Number of metadatas above which we emit an index " 88 "to enable lazy-loading")); 89 static cl::opt<uint32_t> FlushThreshold( 90 "bitcode-flush-threshold", cl::Hidden, cl::init(512), 91 cl::desc("The threshold (unit M) for flushing LLVM bitcode.")); 92 93 static cl::opt<bool> WriteRelBFToSummary( 94 "write-relbf-to-summary", cl::Hidden, cl::init(false), 95 cl::desc("Write relative block frequency to function summary ")); 96 97 extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold; 98 99 namespace { 100 101 /// These are manifest constants used by the bitcode writer. They do not need to 102 /// be kept in sync with the reader, but need to be consistent within this file. 103 enum { 104 // VALUE_SYMTAB_BLOCK abbrev id's. 105 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 106 VST_ENTRY_7_ABBREV, 107 VST_ENTRY_6_ABBREV, 108 VST_BBENTRY_6_ABBREV, 109 110 // CONSTANTS_BLOCK abbrev id's. 111 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 112 CONSTANTS_INTEGER_ABBREV, 113 CONSTANTS_CE_CAST_Abbrev, 114 CONSTANTS_NULL_Abbrev, 115 116 // FUNCTION_BLOCK abbrev id's. 117 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 118 FUNCTION_INST_UNOP_ABBREV, 119 FUNCTION_INST_UNOP_FLAGS_ABBREV, 120 FUNCTION_INST_BINOP_ABBREV, 121 FUNCTION_INST_BINOP_FLAGS_ABBREV, 122 FUNCTION_INST_CAST_ABBREV, 123 FUNCTION_INST_RET_VOID_ABBREV, 124 FUNCTION_INST_RET_VAL_ABBREV, 125 FUNCTION_INST_UNREACHABLE_ABBREV, 126 FUNCTION_INST_GEP_ABBREV, 127 }; 128 129 /// Abstract class to manage the bitcode writing, subclassed for each bitcode 130 /// file type. 131 class BitcodeWriterBase { 132 protected: 133 /// The stream created and owned by the client. 134 BitstreamWriter &Stream; 135 136 StringTableBuilder &StrtabBuilder; 137 138 public: 139 /// Constructs a BitcodeWriterBase object that writes to the provided 140 /// \p Stream. 141 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder) 142 : Stream(Stream), StrtabBuilder(StrtabBuilder) {} 143 144 protected: 145 void writeBitcodeHeader(); 146 void writeModuleVersion(); 147 }; 148 149 void BitcodeWriterBase::writeModuleVersion() { 150 // VERSION: [version#] 151 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2}); 152 } 153 154 /// Base class to manage the module bitcode writing, currently subclassed for 155 /// ModuleBitcodeWriter and ThinLinkBitcodeWriter. 156 class ModuleBitcodeWriterBase : public BitcodeWriterBase { 157 protected: 158 /// The Module to write to bitcode. 159 const Module &M; 160 161 /// Enumerates ids for all values in the module. 162 ValueEnumerator VE; 163 164 /// Optional per-module index to write for ThinLTO. 165 const ModuleSummaryIndex *Index; 166 167 /// Map that holds the correspondence between GUIDs in the summary index, 168 /// that came from indirect call profiles, and a value id generated by this 169 /// class to use in the VST and summary block records. 170 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap; 171 172 /// Tracks the last value id recorded in the GUIDToValueMap. 173 unsigned GlobalValueId; 174 175 /// Saves the offset of the VSTOffset record that must eventually be 176 /// backpatched with the offset of the actual VST. 177 uint64_t VSTOffsetPlaceholder = 0; 178 179 public: 180 /// Constructs a ModuleBitcodeWriterBase object for the given Module, 181 /// writing to the provided \p Buffer. 182 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder, 183 BitstreamWriter &Stream, 184 bool ShouldPreserveUseListOrder, 185 const ModuleSummaryIndex *Index) 186 : BitcodeWriterBase(Stream, StrtabBuilder), M(M), 187 VE(M, ShouldPreserveUseListOrder), Index(Index) { 188 // Assign ValueIds to any callee values in the index that came from 189 // indirect call profiles and were recorded as a GUID not a Value* 190 // (which would have been assigned an ID by the ValueEnumerator). 191 // The starting ValueId is just after the number of values in the 192 // ValueEnumerator, so that they can be emitted in the VST. 193 GlobalValueId = VE.getValues().size(); 194 if (!Index) 195 return; 196 for (const auto &GUIDSummaryLists : *Index) 197 // Examine all summaries for this GUID. 198 for (auto &Summary : GUIDSummaryLists.second.SummaryList) 199 if (auto FS = dyn_cast<FunctionSummary>(Summary.get())) 200 // For each call in the function summary, see if the call 201 // is to a GUID (which means it is for an indirect call, 202 // otherwise we would have a Value for it). If so, synthesize 203 // a value id. 204 for (auto &CallEdge : FS->calls()) 205 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue()) 206 assignValueId(CallEdge.first.getGUID()); 207 } 208 209 protected: 210 void writePerModuleGlobalValueSummary(); 211 212 private: 213 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals, 214 GlobalValueSummary *Summary, 215 unsigned ValueID, 216 unsigned FSCallsAbbrev, 217 unsigned FSCallsProfileAbbrev, 218 const Function &F); 219 void writeModuleLevelReferences(const GlobalVariable &V, 220 SmallVector<uint64_t, 64> &NameVals, 221 unsigned FSModRefsAbbrev, 222 unsigned FSModVTableRefsAbbrev); 223 224 void assignValueId(GlobalValue::GUID ValGUID) { 225 GUIDToValueIdMap[ValGUID] = ++GlobalValueId; 226 } 227 228 unsigned getValueId(GlobalValue::GUID ValGUID) { 229 const auto &VMI = GUIDToValueIdMap.find(ValGUID); 230 // Expect that any GUID value had a value Id assigned by an 231 // earlier call to assignValueId. 232 assert(VMI != GUIDToValueIdMap.end() && 233 "GUID does not have assigned value Id"); 234 return VMI->second; 235 } 236 237 // Helper to get the valueId for the type of value recorded in VI. 238 unsigned getValueId(ValueInfo VI) { 239 if (!VI.haveGVs() || !VI.getValue()) 240 return getValueId(VI.getGUID()); 241 return VE.getValueID(VI.getValue()); 242 } 243 244 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; } 245 }; 246 247 /// Class to manage the bitcode writing for a module. 248 class ModuleBitcodeWriter : public ModuleBitcodeWriterBase { 249 /// Pointer to the buffer allocated by caller for bitcode writing. 250 const SmallVectorImpl<char> &Buffer; 251 252 /// True if a module hash record should be written. 253 bool GenerateHash; 254 255 /// If non-null, when GenerateHash is true, the resulting hash is written 256 /// into ModHash. 257 ModuleHash *ModHash; 258 259 SHA1 Hasher; 260 261 /// The start bit of the identification block. 262 uint64_t BitcodeStartBit; 263 264 public: 265 /// Constructs a ModuleBitcodeWriter object for the given Module, 266 /// writing to the provided \p Buffer. 267 ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer, 268 StringTableBuilder &StrtabBuilder, 269 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder, 270 const ModuleSummaryIndex *Index, bool GenerateHash, 271 ModuleHash *ModHash = nullptr) 272 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream, 273 ShouldPreserveUseListOrder, Index), 274 Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash), 275 BitcodeStartBit(Stream.GetCurrentBitNo()) {} 276 277 /// Emit the current module to the bitstream. 278 void write(); 279 280 private: 281 uint64_t bitcodeStartBit() { return BitcodeStartBit; } 282 283 size_t addToStrtab(StringRef Str); 284 285 void writeAttributeGroupTable(); 286 void writeAttributeTable(); 287 void writeTypeTable(); 288 void writeComdats(); 289 void writeValueSymbolTableForwardDecl(); 290 void writeModuleInfo(); 291 void writeValueAsMetadata(const ValueAsMetadata *MD, 292 SmallVectorImpl<uint64_t> &Record); 293 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record, 294 unsigned Abbrev); 295 unsigned createDILocationAbbrev(); 296 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record, 297 unsigned &Abbrev); 298 unsigned createGenericDINodeAbbrev(); 299 void writeGenericDINode(const GenericDINode *N, 300 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev); 301 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record, 302 unsigned Abbrev); 303 void writeDIGenericSubrange(const DIGenericSubrange *N, 304 SmallVectorImpl<uint64_t> &Record, 305 unsigned Abbrev); 306 void writeDIEnumerator(const DIEnumerator *N, 307 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 308 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record, 309 unsigned Abbrev); 310 void writeDIStringType(const DIStringType *N, 311 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 312 void writeDIDerivedType(const DIDerivedType *N, 313 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 314 void writeDICompositeType(const DICompositeType *N, 315 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 316 void writeDISubroutineType(const DISubroutineType *N, 317 SmallVectorImpl<uint64_t> &Record, 318 unsigned Abbrev); 319 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record, 320 unsigned Abbrev); 321 void writeDICompileUnit(const DICompileUnit *N, 322 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 323 void writeDISubprogram(const DISubprogram *N, 324 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 325 void writeDILexicalBlock(const DILexicalBlock *N, 326 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 327 void writeDILexicalBlockFile(const DILexicalBlockFile *N, 328 SmallVectorImpl<uint64_t> &Record, 329 unsigned Abbrev); 330 void writeDICommonBlock(const DICommonBlock *N, 331 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 332 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record, 333 unsigned Abbrev); 334 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record, 335 unsigned Abbrev); 336 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record, 337 unsigned Abbrev); 338 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record, 339 unsigned Abbrev); 340 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N, 341 SmallVectorImpl<uint64_t> &Record, 342 unsigned Abbrev); 343 void writeDITemplateValueParameter(const DITemplateValueParameter *N, 344 SmallVectorImpl<uint64_t> &Record, 345 unsigned Abbrev); 346 void writeDIGlobalVariable(const DIGlobalVariable *N, 347 SmallVectorImpl<uint64_t> &Record, 348 unsigned Abbrev); 349 void writeDILocalVariable(const DILocalVariable *N, 350 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 351 void writeDILabel(const DILabel *N, 352 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 353 void writeDIExpression(const DIExpression *N, 354 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 355 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N, 356 SmallVectorImpl<uint64_t> &Record, 357 unsigned Abbrev); 358 void writeDIObjCProperty(const DIObjCProperty *N, 359 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 360 void writeDIImportedEntity(const DIImportedEntity *N, 361 SmallVectorImpl<uint64_t> &Record, 362 unsigned Abbrev); 363 unsigned createNamedMetadataAbbrev(); 364 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record); 365 unsigned createMetadataStringsAbbrev(); 366 void writeMetadataStrings(ArrayRef<const Metadata *> Strings, 367 SmallVectorImpl<uint64_t> &Record); 368 void writeMetadataRecords(ArrayRef<const Metadata *> MDs, 369 SmallVectorImpl<uint64_t> &Record, 370 std::vector<unsigned> *MDAbbrevs = nullptr, 371 std::vector<uint64_t> *IndexPos = nullptr); 372 void writeModuleMetadata(); 373 void writeFunctionMetadata(const Function &F); 374 void writeFunctionMetadataAttachment(const Function &F); 375 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV); 376 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record, 377 const GlobalObject &GO); 378 void writeModuleMetadataKinds(); 379 void writeOperandBundleTags(); 380 void writeSyncScopeNames(); 381 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal); 382 void writeModuleConstants(); 383 bool pushValueAndType(const Value *V, unsigned InstID, 384 SmallVectorImpl<unsigned> &Vals); 385 void writeOperandBundles(const CallBase &CB, unsigned InstID); 386 void pushValue(const Value *V, unsigned InstID, 387 SmallVectorImpl<unsigned> &Vals); 388 void pushValueSigned(const Value *V, unsigned InstID, 389 SmallVectorImpl<uint64_t> &Vals); 390 void writeInstruction(const Instruction &I, unsigned InstID, 391 SmallVectorImpl<unsigned> &Vals); 392 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST); 393 void writeGlobalValueSymbolTable( 394 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex); 395 void writeUseList(UseListOrder &&Order); 396 void writeUseListBlock(const Function *F); 397 void 398 writeFunction(const Function &F, 399 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex); 400 void writeBlockInfo(); 401 void writeModuleHash(size_t BlockStartPos); 402 403 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) { 404 return unsigned(SSID); 405 } 406 407 unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); } 408 }; 409 410 /// Class to manage the bitcode writing for a combined index. 411 class IndexBitcodeWriter : public BitcodeWriterBase { 412 /// The combined index to write to bitcode. 413 const ModuleSummaryIndex &Index; 414 415 /// When writing a subset of the index for distributed backends, client 416 /// provides a map of modules to the corresponding GUIDs/summaries to write. 417 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex; 418 419 /// Map that holds the correspondence between the GUID used in the combined 420 /// index and a value id generated by this class to use in references. 421 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap; 422 423 /// Tracks the last value id recorded in the GUIDToValueMap. 424 unsigned GlobalValueId = 0; 425 426 public: 427 /// Constructs a IndexBitcodeWriter object for the given combined index, 428 /// writing to the provided \p Buffer. When writing a subset of the index 429 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map. 430 IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder, 431 const ModuleSummaryIndex &Index, 432 const std::map<std::string, GVSummaryMapTy> 433 *ModuleToSummariesForIndex = nullptr) 434 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index), 435 ModuleToSummariesForIndex(ModuleToSummariesForIndex) { 436 // Assign unique value ids to all summaries to be written, for use 437 // in writing out the call graph edges. Save the mapping from GUID 438 // to the new global value id to use when writing those edges, which 439 // are currently saved in the index in terms of GUID. 440 forEachSummary([&](GVInfo I, bool) { 441 GUIDToValueIdMap[I.first] = ++GlobalValueId; 442 }); 443 } 444 445 /// The below iterator returns the GUID and associated summary. 446 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>; 447 448 /// Calls the callback for each value GUID and summary to be written to 449 /// bitcode. This hides the details of whether they are being pulled from the 450 /// entire index or just those in a provided ModuleToSummariesForIndex map. 451 template<typename Functor> 452 void forEachSummary(Functor Callback) { 453 if (ModuleToSummariesForIndex) { 454 for (auto &M : *ModuleToSummariesForIndex) 455 for (auto &Summary : M.second) { 456 Callback(Summary, false); 457 // Ensure aliasee is handled, e.g. for assigning a valueId, 458 // even if we are not importing the aliasee directly (the 459 // imported alias will contain a copy of aliasee). 460 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond())) 461 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true); 462 } 463 } else { 464 for (auto &Summaries : Index) 465 for (auto &Summary : Summaries.second.SummaryList) 466 Callback({Summaries.first, Summary.get()}, false); 467 } 468 } 469 470 /// Calls the callback for each entry in the modulePaths StringMap that 471 /// should be written to the module path string table. This hides the details 472 /// of whether they are being pulled from the entire index or just those in a 473 /// provided ModuleToSummariesForIndex map. 474 template <typename Functor> void forEachModule(Functor Callback) { 475 if (ModuleToSummariesForIndex) { 476 for (const auto &M : *ModuleToSummariesForIndex) { 477 const auto &MPI = Index.modulePaths().find(M.first); 478 if (MPI == Index.modulePaths().end()) { 479 // This should only happen if the bitcode file was empty, in which 480 // case we shouldn't be importing (the ModuleToSummariesForIndex 481 // would only include the module we are writing and index for). 482 assert(ModuleToSummariesForIndex->size() == 1); 483 continue; 484 } 485 Callback(*MPI); 486 } 487 } else { 488 for (const auto &MPSE : Index.modulePaths()) 489 Callback(MPSE); 490 } 491 } 492 493 /// Main entry point for writing a combined index to bitcode. 494 void write(); 495 496 private: 497 void writeModStrings(); 498 void writeCombinedGlobalValueSummary(); 499 500 Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) { 501 auto VMI = GUIDToValueIdMap.find(ValGUID); 502 if (VMI == GUIDToValueIdMap.end()) 503 return None; 504 return VMI->second; 505 } 506 507 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; } 508 }; 509 510 } // end anonymous namespace 511 512 static unsigned getEncodedCastOpcode(unsigned Opcode) { 513 switch (Opcode) { 514 default: llvm_unreachable("Unknown cast instruction!"); 515 case Instruction::Trunc : return bitc::CAST_TRUNC; 516 case Instruction::ZExt : return bitc::CAST_ZEXT; 517 case Instruction::SExt : return bitc::CAST_SEXT; 518 case Instruction::FPToUI : return bitc::CAST_FPTOUI; 519 case Instruction::FPToSI : return bitc::CAST_FPTOSI; 520 case Instruction::UIToFP : return bitc::CAST_UITOFP; 521 case Instruction::SIToFP : return bitc::CAST_SITOFP; 522 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC; 523 case Instruction::FPExt : return bitc::CAST_FPEXT; 524 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT; 525 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR; 526 case Instruction::BitCast : return bitc::CAST_BITCAST; 527 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST; 528 } 529 } 530 531 static unsigned getEncodedUnaryOpcode(unsigned Opcode) { 532 switch (Opcode) { 533 default: llvm_unreachable("Unknown binary instruction!"); 534 case Instruction::FNeg: return bitc::UNOP_FNEG; 535 } 536 } 537 538 static unsigned getEncodedBinaryOpcode(unsigned Opcode) { 539 switch (Opcode) { 540 default: llvm_unreachable("Unknown binary instruction!"); 541 case Instruction::Add: 542 case Instruction::FAdd: return bitc::BINOP_ADD; 543 case Instruction::Sub: 544 case Instruction::FSub: return bitc::BINOP_SUB; 545 case Instruction::Mul: 546 case Instruction::FMul: return bitc::BINOP_MUL; 547 case Instruction::UDiv: return bitc::BINOP_UDIV; 548 case Instruction::FDiv: 549 case Instruction::SDiv: return bitc::BINOP_SDIV; 550 case Instruction::URem: return bitc::BINOP_UREM; 551 case Instruction::FRem: 552 case Instruction::SRem: return bitc::BINOP_SREM; 553 case Instruction::Shl: return bitc::BINOP_SHL; 554 case Instruction::LShr: return bitc::BINOP_LSHR; 555 case Instruction::AShr: return bitc::BINOP_ASHR; 556 case Instruction::And: return bitc::BINOP_AND; 557 case Instruction::Or: return bitc::BINOP_OR; 558 case Instruction::Xor: return bitc::BINOP_XOR; 559 } 560 } 561 562 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) { 563 switch (Op) { 564 default: llvm_unreachable("Unknown RMW operation!"); 565 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG; 566 case AtomicRMWInst::Add: return bitc::RMW_ADD; 567 case AtomicRMWInst::Sub: return bitc::RMW_SUB; 568 case AtomicRMWInst::And: return bitc::RMW_AND; 569 case AtomicRMWInst::Nand: return bitc::RMW_NAND; 570 case AtomicRMWInst::Or: return bitc::RMW_OR; 571 case AtomicRMWInst::Xor: return bitc::RMW_XOR; 572 case AtomicRMWInst::Max: return bitc::RMW_MAX; 573 case AtomicRMWInst::Min: return bitc::RMW_MIN; 574 case AtomicRMWInst::UMax: return bitc::RMW_UMAX; 575 case AtomicRMWInst::UMin: return bitc::RMW_UMIN; 576 case AtomicRMWInst::FAdd: return bitc::RMW_FADD; 577 case AtomicRMWInst::FSub: return bitc::RMW_FSUB; 578 } 579 } 580 581 static unsigned getEncodedOrdering(AtomicOrdering Ordering) { 582 switch (Ordering) { 583 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC; 584 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED; 585 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC; 586 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE; 587 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE; 588 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL; 589 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST; 590 } 591 llvm_unreachable("Invalid ordering"); 592 } 593 594 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, 595 StringRef Str, unsigned AbbrevToUse) { 596 SmallVector<unsigned, 64> Vals; 597 598 // Code: [strchar x N] 599 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 600 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i])) 601 AbbrevToUse = 0; 602 Vals.push_back(Str[i]); 603 } 604 605 // Emit the finished record. 606 Stream.EmitRecord(Code, Vals, AbbrevToUse); 607 } 608 609 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) { 610 switch (Kind) { 611 case Attribute::Alignment: 612 return bitc::ATTR_KIND_ALIGNMENT; 613 case Attribute::AllocSize: 614 return bitc::ATTR_KIND_ALLOC_SIZE; 615 case Attribute::AlwaysInline: 616 return bitc::ATTR_KIND_ALWAYS_INLINE; 617 case Attribute::ArgMemOnly: 618 return bitc::ATTR_KIND_ARGMEMONLY; 619 case Attribute::Builtin: 620 return bitc::ATTR_KIND_BUILTIN; 621 case Attribute::ByVal: 622 return bitc::ATTR_KIND_BY_VAL; 623 case Attribute::Convergent: 624 return bitc::ATTR_KIND_CONVERGENT; 625 case Attribute::InAlloca: 626 return bitc::ATTR_KIND_IN_ALLOCA; 627 case Attribute::Cold: 628 return bitc::ATTR_KIND_COLD; 629 case Attribute::InaccessibleMemOnly: 630 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY; 631 case Attribute::InaccessibleMemOrArgMemOnly: 632 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY; 633 case Attribute::InlineHint: 634 return bitc::ATTR_KIND_INLINE_HINT; 635 case Attribute::InReg: 636 return bitc::ATTR_KIND_IN_REG; 637 case Attribute::JumpTable: 638 return bitc::ATTR_KIND_JUMP_TABLE; 639 case Attribute::MinSize: 640 return bitc::ATTR_KIND_MIN_SIZE; 641 case Attribute::Naked: 642 return bitc::ATTR_KIND_NAKED; 643 case Attribute::Nest: 644 return bitc::ATTR_KIND_NEST; 645 case Attribute::NoAlias: 646 return bitc::ATTR_KIND_NO_ALIAS; 647 case Attribute::NoBuiltin: 648 return bitc::ATTR_KIND_NO_BUILTIN; 649 case Attribute::NoCapture: 650 return bitc::ATTR_KIND_NO_CAPTURE; 651 case Attribute::NoDuplicate: 652 return bitc::ATTR_KIND_NO_DUPLICATE; 653 case Attribute::NoFree: 654 return bitc::ATTR_KIND_NOFREE; 655 case Attribute::NoImplicitFloat: 656 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT; 657 case Attribute::NoInline: 658 return bitc::ATTR_KIND_NO_INLINE; 659 case Attribute::NoRecurse: 660 return bitc::ATTR_KIND_NO_RECURSE; 661 case Attribute::NoMerge: 662 return bitc::ATTR_KIND_NO_MERGE; 663 case Attribute::NonLazyBind: 664 return bitc::ATTR_KIND_NON_LAZY_BIND; 665 case Attribute::NonNull: 666 return bitc::ATTR_KIND_NON_NULL; 667 case Attribute::Dereferenceable: 668 return bitc::ATTR_KIND_DEREFERENCEABLE; 669 case Attribute::DereferenceableOrNull: 670 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL; 671 case Attribute::NoRedZone: 672 return bitc::ATTR_KIND_NO_RED_ZONE; 673 case Attribute::NoReturn: 674 return bitc::ATTR_KIND_NO_RETURN; 675 case Attribute::NoSync: 676 return bitc::ATTR_KIND_NOSYNC; 677 case Attribute::NoCfCheck: 678 return bitc::ATTR_KIND_NOCF_CHECK; 679 case Attribute::NoUnwind: 680 return bitc::ATTR_KIND_NO_UNWIND; 681 case Attribute::NullPointerIsValid: 682 return bitc::ATTR_KIND_NULL_POINTER_IS_VALID; 683 case Attribute::OptForFuzzing: 684 return bitc::ATTR_KIND_OPT_FOR_FUZZING; 685 case Attribute::OptimizeForSize: 686 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE; 687 case Attribute::OptimizeNone: 688 return bitc::ATTR_KIND_OPTIMIZE_NONE; 689 case Attribute::ReadNone: 690 return bitc::ATTR_KIND_READ_NONE; 691 case Attribute::ReadOnly: 692 return bitc::ATTR_KIND_READ_ONLY; 693 case Attribute::Returned: 694 return bitc::ATTR_KIND_RETURNED; 695 case Attribute::ReturnsTwice: 696 return bitc::ATTR_KIND_RETURNS_TWICE; 697 case Attribute::SExt: 698 return bitc::ATTR_KIND_S_EXT; 699 case Attribute::Speculatable: 700 return bitc::ATTR_KIND_SPECULATABLE; 701 case Attribute::StackAlignment: 702 return bitc::ATTR_KIND_STACK_ALIGNMENT; 703 case Attribute::StackProtect: 704 return bitc::ATTR_KIND_STACK_PROTECT; 705 case Attribute::StackProtectReq: 706 return bitc::ATTR_KIND_STACK_PROTECT_REQ; 707 case Attribute::StackProtectStrong: 708 return bitc::ATTR_KIND_STACK_PROTECT_STRONG; 709 case Attribute::SafeStack: 710 return bitc::ATTR_KIND_SAFESTACK; 711 case Attribute::ShadowCallStack: 712 return bitc::ATTR_KIND_SHADOWCALLSTACK; 713 case Attribute::StrictFP: 714 return bitc::ATTR_KIND_STRICT_FP; 715 case Attribute::StructRet: 716 return bitc::ATTR_KIND_STRUCT_RET; 717 case Attribute::SanitizeAddress: 718 return bitc::ATTR_KIND_SANITIZE_ADDRESS; 719 case Attribute::SanitizeHWAddress: 720 return bitc::ATTR_KIND_SANITIZE_HWADDRESS; 721 case Attribute::SanitizeThread: 722 return bitc::ATTR_KIND_SANITIZE_THREAD; 723 case Attribute::SanitizeMemory: 724 return bitc::ATTR_KIND_SANITIZE_MEMORY; 725 case Attribute::SpeculativeLoadHardening: 726 return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING; 727 case Attribute::SwiftError: 728 return bitc::ATTR_KIND_SWIFT_ERROR; 729 case Attribute::SwiftSelf: 730 return bitc::ATTR_KIND_SWIFT_SELF; 731 case Attribute::UWTable: 732 return bitc::ATTR_KIND_UW_TABLE; 733 case Attribute::WillReturn: 734 return bitc::ATTR_KIND_WILLRETURN; 735 case Attribute::WriteOnly: 736 return bitc::ATTR_KIND_WRITEONLY; 737 case Attribute::ZExt: 738 return bitc::ATTR_KIND_Z_EXT; 739 case Attribute::ImmArg: 740 return bitc::ATTR_KIND_IMMARG; 741 case Attribute::SanitizeMemTag: 742 return bitc::ATTR_KIND_SANITIZE_MEMTAG; 743 case Attribute::Preallocated: 744 return bitc::ATTR_KIND_PREALLOCATED; 745 case Attribute::NoUndef: 746 return bitc::ATTR_KIND_NOUNDEF; 747 case Attribute::ByRef: 748 return bitc::ATTR_KIND_BYREF; 749 case Attribute::MustProgress: 750 return bitc::ATTR_KIND_MUSTPROGRESS; 751 case Attribute::EndAttrKinds: 752 llvm_unreachable("Can not encode end-attribute kinds marker."); 753 case Attribute::None: 754 llvm_unreachable("Can not encode none-attribute."); 755 case Attribute::EmptyKey: 756 case Attribute::TombstoneKey: 757 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey"); 758 } 759 760 llvm_unreachable("Trying to encode unknown attribute"); 761 } 762 763 void ModuleBitcodeWriter::writeAttributeGroupTable() { 764 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps = 765 VE.getAttributeGroups(); 766 if (AttrGrps.empty()) return; 767 768 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3); 769 770 SmallVector<uint64_t, 64> Record; 771 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) { 772 unsigned AttrListIndex = Pair.first; 773 AttributeSet AS = Pair.second; 774 Record.push_back(VE.getAttributeGroupID(Pair)); 775 Record.push_back(AttrListIndex); 776 777 for (Attribute Attr : AS) { 778 if (Attr.isEnumAttribute()) { 779 Record.push_back(0); 780 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 781 } else if (Attr.isIntAttribute()) { 782 Record.push_back(1); 783 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 784 Record.push_back(Attr.getValueAsInt()); 785 } else if (Attr.isStringAttribute()) { 786 StringRef Kind = Attr.getKindAsString(); 787 StringRef Val = Attr.getValueAsString(); 788 789 Record.push_back(Val.empty() ? 3 : 4); 790 Record.append(Kind.begin(), Kind.end()); 791 Record.push_back(0); 792 if (!Val.empty()) { 793 Record.append(Val.begin(), Val.end()); 794 Record.push_back(0); 795 } 796 } else { 797 assert(Attr.isTypeAttribute()); 798 Type *Ty = Attr.getValueAsType(); 799 Record.push_back(Ty ? 6 : 5); 800 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 801 if (Ty) 802 Record.push_back(VE.getTypeID(Attr.getValueAsType())); 803 } 804 } 805 806 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record); 807 Record.clear(); 808 } 809 810 Stream.ExitBlock(); 811 } 812 813 void ModuleBitcodeWriter::writeAttributeTable() { 814 const std::vector<AttributeList> &Attrs = VE.getAttributeLists(); 815 if (Attrs.empty()) return; 816 817 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3); 818 819 SmallVector<uint64_t, 64> Record; 820 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) { 821 AttributeList AL = Attrs[i]; 822 for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) { 823 AttributeSet AS = AL.getAttributes(i); 824 if (AS.hasAttributes()) 825 Record.push_back(VE.getAttributeGroupID({i, AS})); 826 } 827 828 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record); 829 Record.clear(); 830 } 831 832 Stream.ExitBlock(); 833 } 834 835 /// WriteTypeTable - Write out the type table for a module. 836 void ModuleBitcodeWriter::writeTypeTable() { 837 const ValueEnumerator::TypeList &TypeList = VE.getTypes(); 838 839 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */); 840 SmallVector<uint64_t, 64> TypeVals; 841 842 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies(); 843 844 // Abbrev for TYPE_CODE_POINTER. 845 auto Abbv = std::make_shared<BitCodeAbbrev>(); 846 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER)); 847 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 848 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0 849 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 850 851 // Abbrev for TYPE_CODE_FUNCTION. 852 Abbv = std::make_shared<BitCodeAbbrev>(); 853 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION)); 854 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg 855 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 856 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 857 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 858 859 // Abbrev for TYPE_CODE_STRUCT_ANON. 860 Abbv = std::make_shared<BitCodeAbbrev>(); 861 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON)); 862 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 863 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 864 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 865 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 866 867 // Abbrev for TYPE_CODE_STRUCT_NAME. 868 Abbv = std::make_shared<BitCodeAbbrev>(); 869 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME)); 870 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 871 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 872 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 873 874 // Abbrev for TYPE_CODE_STRUCT_NAMED. 875 Abbv = std::make_shared<BitCodeAbbrev>(); 876 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED)); 877 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 878 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 879 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 880 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 881 882 // Abbrev for TYPE_CODE_ARRAY. 883 Abbv = std::make_shared<BitCodeAbbrev>(); 884 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY)); 885 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size 886 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 887 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 888 889 // Emit an entry count so the reader can reserve space. 890 TypeVals.push_back(TypeList.size()); 891 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals); 892 TypeVals.clear(); 893 894 // Loop over all of the types, emitting each in turn. 895 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { 896 Type *T = TypeList[i]; 897 int AbbrevToUse = 0; 898 unsigned Code = 0; 899 900 switch (T->getTypeID()) { 901 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break; 902 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break; 903 case Type::BFloatTyID: Code = bitc::TYPE_CODE_BFLOAT; break; 904 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break; 905 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break; 906 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break; 907 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break; 908 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break; 909 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break; 910 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break; 911 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break; 912 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break; 913 case Type::IntegerTyID: 914 // INTEGER: [width] 915 Code = bitc::TYPE_CODE_INTEGER; 916 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 917 break; 918 case Type::PointerTyID: { 919 PointerType *PTy = cast<PointerType>(T); 920 // POINTER: [pointee type, address space] 921 Code = bitc::TYPE_CODE_POINTER; 922 TypeVals.push_back(VE.getTypeID(PTy->getElementType())); 923 unsigned AddressSpace = PTy->getAddressSpace(); 924 TypeVals.push_back(AddressSpace); 925 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev; 926 break; 927 } 928 case Type::FunctionTyID: { 929 FunctionType *FT = cast<FunctionType>(T); 930 // FUNCTION: [isvararg, retty, paramty x N] 931 Code = bitc::TYPE_CODE_FUNCTION; 932 TypeVals.push_back(FT->isVarArg()); 933 TypeVals.push_back(VE.getTypeID(FT->getReturnType())); 934 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) 935 TypeVals.push_back(VE.getTypeID(FT->getParamType(i))); 936 AbbrevToUse = FunctionAbbrev; 937 break; 938 } 939 case Type::StructTyID: { 940 StructType *ST = cast<StructType>(T); 941 // STRUCT: [ispacked, eltty x N] 942 TypeVals.push_back(ST->isPacked()); 943 // Output all of the element types. 944 for (StructType::element_iterator I = ST->element_begin(), 945 E = ST->element_end(); I != E; ++I) 946 TypeVals.push_back(VE.getTypeID(*I)); 947 948 if (ST->isLiteral()) { 949 Code = bitc::TYPE_CODE_STRUCT_ANON; 950 AbbrevToUse = StructAnonAbbrev; 951 } else { 952 if (ST->isOpaque()) { 953 Code = bitc::TYPE_CODE_OPAQUE; 954 } else { 955 Code = bitc::TYPE_CODE_STRUCT_NAMED; 956 AbbrevToUse = StructNamedAbbrev; 957 } 958 959 // Emit the name if it is present. 960 if (!ST->getName().empty()) 961 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(), 962 StructNameAbbrev); 963 } 964 break; 965 } 966 case Type::ArrayTyID: { 967 ArrayType *AT = cast<ArrayType>(T); 968 // ARRAY: [numelts, eltty] 969 Code = bitc::TYPE_CODE_ARRAY; 970 TypeVals.push_back(AT->getNumElements()); 971 TypeVals.push_back(VE.getTypeID(AT->getElementType())); 972 AbbrevToUse = ArrayAbbrev; 973 break; 974 } 975 case Type::FixedVectorTyID: 976 case Type::ScalableVectorTyID: { 977 VectorType *VT = cast<VectorType>(T); 978 // VECTOR [numelts, eltty] or 979 // [numelts, eltty, scalable] 980 Code = bitc::TYPE_CODE_VECTOR; 981 TypeVals.push_back(VT->getElementCount().getKnownMinValue()); 982 TypeVals.push_back(VE.getTypeID(VT->getElementType())); 983 if (isa<ScalableVectorType>(VT)) 984 TypeVals.push_back(true); 985 break; 986 } 987 } 988 989 // Emit the finished record. 990 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 991 TypeVals.clear(); 992 } 993 994 Stream.ExitBlock(); 995 } 996 997 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) { 998 switch (Linkage) { 999 case GlobalValue::ExternalLinkage: 1000 return 0; 1001 case GlobalValue::WeakAnyLinkage: 1002 return 16; 1003 case GlobalValue::AppendingLinkage: 1004 return 2; 1005 case GlobalValue::InternalLinkage: 1006 return 3; 1007 case GlobalValue::LinkOnceAnyLinkage: 1008 return 18; 1009 case GlobalValue::ExternalWeakLinkage: 1010 return 7; 1011 case GlobalValue::CommonLinkage: 1012 return 8; 1013 case GlobalValue::PrivateLinkage: 1014 return 9; 1015 case GlobalValue::WeakODRLinkage: 1016 return 17; 1017 case GlobalValue::LinkOnceODRLinkage: 1018 return 19; 1019 case GlobalValue::AvailableExternallyLinkage: 1020 return 12; 1021 } 1022 llvm_unreachable("Invalid linkage"); 1023 } 1024 1025 static unsigned getEncodedLinkage(const GlobalValue &GV) { 1026 return getEncodedLinkage(GV.getLinkage()); 1027 } 1028 1029 static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) { 1030 uint64_t RawFlags = 0; 1031 RawFlags |= Flags.ReadNone; 1032 RawFlags |= (Flags.ReadOnly << 1); 1033 RawFlags |= (Flags.NoRecurse << 2); 1034 RawFlags |= (Flags.ReturnDoesNotAlias << 3); 1035 RawFlags |= (Flags.NoInline << 4); 1036 RawFlags |= (Flags.AlwaysInline << 5); 1037 return RawFlags; 1038 } 1039 1040 // Decode the flags for GlobalValue in the summary 1041 static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) { 1042 uint64_t RawFlags = 0; 1043 1044 RawFlags |= Flags.NotEligibleToImport; // bool 1045 RawFlags |= (Flags.Live << 1); 1046 RawFlags |= (Flags.DSOLocal << 2); 1047 RawFlags |= (Flags.CanAutoHide << 3); 1048 1049 // Linkage don't need to be remapped at that time for the summary. Any future 1050 // change to the getEncodedLinkage() function will need to be taken into 1051 // account here as well. 1052 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits 1053 1054 return RawFlags; 1055 } 1056 1057 static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) { 1058 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) | 1059 (Flags.Constant << 2) | Flags.VCallVisibility << 3; 1060 return RawFlags; 1061 } 1062 1063 static unsigned getEncodedVisibility(const GlobalValue &GV) { 1064 switch (GV.getVisibility()) { 1065 case GlobalValue::DefaultVisibility: return 0; 1066 case GlobalValue::HiddenVisibility: return 1; 1067 case GlobalValue::ProtectedVisibility: return 2; 1068 } 1069 llvm_unreachable("Invalid visibility"); 1070 } 1071 1072 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) { 1073 switch (GV.getDLLStorageClass()) { 1074 case GlobalValue::DefaultStorageClass: return 0; 1075 case GlobalValue::DLLImportStorageClass: return 1; 1076 case GlobalValue::DLLExportStorageClass: return 2; 1077 } 1078 llvm_unreachable("Invalid DLL storage class"); 1079 } 1080 1081 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) { 1082 switch (GV.getThreadLocalMode()) { 1083 case GlobalVariable::NotThreadLocal: return 0; 1084 case GlobalVariable::GeneralDynamicTLSModel: return 1; 1085 case GlobalVariable::LocalDynamicTLSModel: return 2; 1086 case GlobalVariable::InitialExecTLSModel: return 3; 1087 case GlobalVariable::LocalExecTLSModel: return 4; 1088 } 1089 llvm_unreachable("Invalid TLS model"); 1090 } 1091 1092 static unsigned getEncodedComdatSelectionKind(const Comdat &C) { 1093 switch (C.getSelectionKind()) { 1094 case Comdat::Any: 1095 return bitc::COMDAT_SELECTION_KIND_ANY; 1096 case Comdat::ExactMatch: 1097 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH; 1098 case Comdat::Largest: 1099 return bitc::COMDAT_SELECTION_KIND_LARGEST; 1100 case Comdat::NoDuplicates: 1101 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES; 1102 case Comdat::SameSize: 1103 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE; 1104 } 1105 llvm_unreachable("Invalid selection kind"); 1106 } 1107 1108 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) { 1109 switch (GV.getUnnamedAddr()) { 1110 case GlobalValue::UnnamedAddr::None: return 0; 1111 case GlobalValue::UnnamedAddr::Local: return 2; 1112 case GlobalValue::UnnamedAddr::Global: return 1; 1113 } 1114 llvm_unreachable("Invalid unnamed_addr"); 1115 } 1116 1117 size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) { 1118 if (GenerateHash) 1119 Hasher.update(Str); 1120 return StrtabBuilder.add(Str); 1121 } 1122 1123 void ModuleBitcodeWriter::writeComdats() { 1124 SmallVector<unsigned, 64> Vals; 1125 for (const Comdat *C : VE.getComdats()) { 1126 // COMDAT: [strtab offset, strtab size, selection_kind] 1127 Vals.push_back(addToStrtab(C->getName())); 1128 Vals.push_back(C->getName().size()); 1129 Vals.push_back(getEncodedComdatSelectionKind(*C)); 1130 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0); 1131 Vals.clear(); 1132 } 1133 } 1134 1135 /// Write a record that will eventually hold the word offset of the 1136 /// module-level VST. For now the offset is 0, which will be backpatched 1137 /// after the real VST is written. Saves the bit offset to backpatch. 1138 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() { 1139 // Write a placeholder value in for the offset of the real VST, 1140 // which is written after the function blocks so that it can include 1141 // the offset of each function. The placeholder offset will be 1142 // updated when the real VST is written. 1143 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1144 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET)); 1145 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to 1146 // hold the real VST offset. Must use fixed instead of VBR as we don't 1147 // know how many VBR chunks to reserve ahead of time. 1148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1149 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1150 1151 // Emit the placeholder 1152 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0}; 1153 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals); 1154 1155 // Compute and save the bit offset to the placeholder, which will be 1156 // patched when the real VST is written. We can simply subtract the 32-bit 1157 // fixed size from the current bit number to get the location to backpatch. 1158 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32; 1159 } 1160 1161 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 }; 1162 1163 /// Determine the encoding to use for the given string name and length. 1164 static StringEncoding getStringEncoding(StringRef Str) { 1165 bool isChar6 = true; 1166 for (char C : Str) { 1167 if (isChar6) 1168 isChar6 = BitCodeAbbrevOp::isChar6(C); 1169 if ((unsigned char)C & 128) 1170 // don't bother scanning the rest. 1171 return SE_Fixed8; 1172 } 1173 if (isChar6) 1174 return SE_Char6; 1175 return SE_Fixed7; 1176 } 1177 1178 /// Emit top-level description of module, including target triple, inline asm, 1179 /// descriptors for global variables, and function prototype info. 1180 /// Returns the bit offset to backpatch with the location of the real VST. 1181 void ModuleBitcodeWriter::writeModuleInfo() { 1182 // Emit various pieces of data attached to a module. 1183 if (!M.getTargetTriple().empty()) 1184 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(), 1185 0 /*TODO*/); 1186 const std::string &DL = M.getDataLayoutStr(); 1187 if (!DL.empty()) 1188 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/); 1189 if (!M.getModuleInlineAsm().empty()) 1190 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(), 1191 0 /*TODO*/); 1192 1193 // Emit information about sections and GC, computing how many there are. Also 1194 // compute the maximum alignment value. 1195 std::map<std::string, unsigned> SectionMap; 1196 std::map<std::string, unsigned> GCMap; 1197 MaybeAlign MaxAlignment; 1198 unsigned MaxGlobalType = 0; 1199 const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) { 1200 if (A) 1201 MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A); 1202 }; 1203 for (const GlobalVariable &GV : M.globals()) { 1204 UpdateMaxAlignment(GV.getAlign()); 1205 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType())); 1206 if (GV.hasSection()) { 1207 // Give section names unique ID's. 1208 unsigned &Entry = SectionMap[std::string(GV.getSection())]; 1209 if (!Entry) { 1210 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(), 1211 0 /*TODO*/); 1212 Entry = SectionMap.size(); 1213 } 1214 } 1215 } 1216 for (const Function &F : M) { 1217 UpdateMaxAlignment(F.getAlign()); 1218 if (F.hasSection()) { 1219 // Give section names unique ID's. 1220 unsigned &Entry = SectionMap[std::string(F.getSection())]; 1221 if (!Entry) { 1222 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(), 1223 0 /*TODO*/); 1224 Entry = SectionMap.size(); 1225 } 1226 } 1227 if (F.hasGC()) { 1228 // Same for GC names. 1229 unsigned &Entry = GCMap[F.getGC()]; 1230 if (!Entry) { 1231 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(), 1232 0 /*TODO*/); 1233 Entry = GCMap.size(); 1234 } 1235 } 1236 } 1237 1238 // Emit abbrev for globals, now that we know # sections and max alignment. 1239 unsigned SimpleGVarAbbrev = 0; 1240 if (!M.global_empty()) { 1241 // Add an abbrev for common globals with no visibility or thread localness. 1242 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1243 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 1244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1245 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1246 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1247 Log2_32_Ceil(MaxGlobalType+1))); 1248 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2 1249 //| explicitType << 1 1250 //| constant 1251 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 1252 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage. 1253 if (!MaxAlignment) // Alignment. 1254 Abbv->Add(BitCodeAbbrevOp(0)); 1255 else { 1256 unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment); 1257 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1258 Log2_32_Ceil(MaxEncAlignment+1))); 1259 } 1260 if (SectionMap.empty()) // Section. 1261 Abbv->Add(BitCodeAbbrevOp(0)); 1262 else 1263 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1264 Log2_32_Ceil(SectionMap.size()+1))); 1265 // Don't bother emitting vis + thread local. 1266 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1267 } 1268 1269 SmallVector<unsigned, 64> Vals; 1270 // Emit the module's source file name. 1271 { 1272 StringEncoding Bits = getStringEncoding(M.getSourceFileName()); 1273 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8); 1274 if (Bits == SE_Char6) 1275 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6); 1276 else if (Bits == SE_Fixed7) 1277 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7); 1278 1279 // MODULE_CODE_SOURCE_FILENAME: [namechar x N] 1280 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1281 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME)); 1282 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1283 Abbv->Add(AbbrevOpToUse); 1284 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1285 1286 for (const auto P : M.getSourceFileName()) 1287 Vals.push_back((unsigned char)P); 1288 1289 // Emit the finished record. 1290 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev); 1291 Vals.clear(); 1292 } 1293 1294 // Emit the global variable information. 1295 for (const GlobalVariable &GV : M.globals()) { 1296 unsigned AbbrevToUse = 0; 1297 1298 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid, 1299 // linkage, alignment, section, visibility, threadlocal, 1300 // unnamed_addr, externally_initialized, dllstorageclass, 1301 // comdat, attributes, DSO_Local] 1302 Vals.push_back(addToStrtab(GV.getName())); 1303 Vals.push_back(GV.getName().size()); 1304 Vals.push_back(VE.getTypeID(GV.getValueType())); 1305 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant()); 1306 Vals.push_back(GV.isDeclaration() ? 0 : 1307 (VE.getValueID(GV.getInitializer()) + 1)); 1308 Vals.push_back(getEncodedLinkage(GV)); 1309 Vals.push_back(getEncodedAlign(GV.getAlign())); 1310 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())] 1311 : 0); 1312 if (GV.isThreadLocal() || 1313 GV.getVisibility() != GlobalValue::DefaultVisibility || 1314 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None || 1315 GV.isExternallyInitialized() || 1316 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass || 1317 GV.hasComdat() || 1318 GV.hasAttributes() || 1319 GV.isDSOLocal() || 1320 GV.hasPartition()) { 1321 Vals.push_back(getEncodedVisibility(GV)); 1322 Vals.push_back(getEncodedThreadLocalMode(GV)); 1323 Vals.push_back(getEncodedUnnamedAddr(GV)); 1324 Vals.push_back(GV.isExternallyInitialized()); 1325 Vals.push_back(getEncodedDLLStorageClass(GV)); 1326 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0); 1327 1328 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex); 1329 Vals.push_back(VE.getAttributeListID(AL)); 1330 1331 Vals.push_back(GV.isDSOLocal()); 1332 Vals.push_back(addToStrtab(GV.getPartition())); 1333 Vals.push_back(GV.getPartition().size()); 1334 } else { 1335 AbbrevToUse = SimpleGVarAbbrev; 1336 } 1337 1338 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 1339 Vals.clear(); 1340 } 1341 1342 // Emit the function proto information. 1343 for (const Function &F : M) { 1344 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto, 1345 // linkage, paramattrs, alignment, section, visibility, gc, 1346 // unnamed_addr, prologuedata, dllstorageclass, comdat, 1347 // prefixdata, personalityfn, DSO_Local, addrspace] 1348 Vals.push_back(addToStrtab(F.getName())); 1349 Vals.push_back(F.getName().size()); 1350 Vals.push_back(VE.getTypeID(F.getFunctionType())); 1351 Vals.push_back(F.getCallingConv()); 1352 Vals.push_back(F.isDeclaration()); 1353 Vals.push_back(getEncodedLinkage(F)); 1354 Vals.push_back(VE.getAttributeListID(F.getAttributes())); 1355 Vals.push_back(getEncodedAlign(F.getAlign())); 1356 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())] 1357 : 0); 1358 Vals.push_back(getEncodedVisibility(F)); 1359 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0); 1360 Vals.push_back(getEncodedUnnamedAddr(F)); 1361 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1) 1362 : 0); 1363 Vals.push_back(getEncodedDLLStorageClass(F)); 1364 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0); 1365 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1) 1366 : 0); 1367 Vals.push_back( 1368 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0); 1369 1370 Vals.push_back(F.isDSOLocal()); 1371 Vals.push_back(F.getAddressSpace()); 1372 Vals.push_back(addToStrtab(F.getPartition())); 1373 Vals.push_back(F.getPartition().size()); 1374 1375 unsigned AbbrevToUse = 0; 1376 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 1377 Vals.clear(); 1378 } 1379 1380 // Emit the alias information. 1381 for (const GlobalAlias &A : M.aliases()) { 1382 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage, 1383 // visibility, dllstorageclass, threadlocal, unnamed_addr, 1384 // DSO_Local] 1385 Vals.push_back(addToStrtab(A.getName())); 1386 Vals.push_back(A.getName().size()); 1387 Vals.push_back(VE.getTypeID(A.getValueType())); 1388 Vals.push_back(A.getType()->getAddressSpace()); 1389 Vals.push_back(VE.getValueID(A.getAliasee())); 1390 Vals.push_back(getEncodedLinkage(A)); 1391 Vals.push_back(getEncodedVisibility(A)); 1392 Vals.push_back(getEncodedDLLStorageClass(A)); 1393 Vals.push_back(getEncodedThreadLocalMode(A)); 1394 Vals.push_back(getEncodedUnnamedAddr(A)); 1395 Vals.push_back(A.isDSOLocal()); 1396 Vals.push_back(addToStrtab(A.getPartition())); 1397 Vals.push_back(A.getPartition().size()); 1398 1399 unsigned AbbrevToUse = 0; 1400 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse); 1401 Vals.clear(); 1402 } 1403 1404 // Emit the ifunc information. 1405 for (const GlobalIFunc &I : M.ifuncs()) { 1406 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver 1407 // val#, linkage, visibility, DSO_Local] 1408 Vals.push_back(addToStrtab(I.getName())); 1409 Vals.push_back(I.getName().size()); 1410 Vals.push_back(VE.getTypeID(I.getValueType())); 1411 Vals.push_back(I.getType()->getAddressSpace()); 1412 Vals.push_back(VE.getValueID(I.getResolver())); 1413 Vals.push_back(getEncodedLinkage(I)); 1414 Vals.push_back(getEncodedVisibility(I)); 1415 Vals.push_back(I.isDSOLocal()); 1416 Vals.push_back(addToStrtab(I.getPartition())); 1417 Vals.push_back(I.getPartition().size()); 1418 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals); 1419 Vals.clear(); 1420 } 1421 1422 writeValueSymbolTableForwardDecl(); 1423 } 1424 1425 static uint64_t getOptimizationFlags(const Value *V) { 1426 uint64_t Flags = 0; 1427 1428 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) { 1429 if (OBO->hasNoSignedWrap()) 1430 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP; 1431 if (OBO->hasNoUnsignedWrap()) 1432 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP; 1433 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) { 1434 if (PEO->isExact()) 1435 Flags |= 1 << bitc::PEO_EXACT; 1436 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) { 1437 if (FPMO->hasAllowReassoc()) 1438 Flags |= bitc::AllowReassoc; 1439 if (FPMO->hasNoNaNs()) 1440 Flags |= bitc::NoNaNs; 1441 if (FPMO->hasNoInfs()) 1442 Flags |= bitc::NoInfs; 1443 if (FPMO->hasNoSignedZeros()) 1444 Flags |= bitc::NoSignedZeros; 1445 if (FPMO->hasAllowReciprocal()) 1446 Flags |= bitc::AllowReciprocal; 1447 if (FPMO->hasAllowContract()) 1448 Flags |= bitc::AllowContract; 1449 if (FPMO->hasApproxFunc()) 1450 Flags |= bitc::ApproxFunc; 1451 } 1452 1453 return Flags; 1454 } 1455 1456 void ModuleBitcodeWriter::writeValueAsMetadata( 1457 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) { 1458 // Mimic an MDNode with a value as one operand. 1459 Value *V = MD->getValue(); 1460 Record.push_back(VE.getTypeID(V->getType())); 1461 Record.push_back(VE.getValueID(V)); 1462 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0); 1463 Record.clear(); 1464 } 1465 1466 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N, 1467 SmallVectorImpl<uint64_t> &Record, 1468 unsigned Abbrev) { 1469 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1470 Metadata *MD = N->getOperand(i); 1471 assert(!(MD && isa<LocalAsMetadata>(MD)) && 1472 "Unexpected function-local metadata"); 1473 Record.push_back(VE.getMetadataOrNullID(MD)); 1474 } 1475 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE 1476 : bitc::METADATA_NODE, 1477 Record, Abbrev); 1478 Record.clear(); 1479 } 1480 1481 unsigned ModuleBitcodeWriter::createDILocationAbbrev() { 1482 // Assume the column is usually under 128, and always output the inlined-at 1483 // location (it's never more expensive than building an array size 1). 1484 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1485 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION)); 1486 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1487 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1488 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1489 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1490 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1491 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1492 return Stream.EmitAbbrev(std::move(Abbv)); 1493 } 1494 1495 void ModuleBitcodeWriter::writeDILocation(const DILocation *N, 1496 SmallVectorImpl<uint64_t> &Record, 1497 unsigned &Abbrev) { 1498 if (!Abbrev) 1499 Abbrev = createDILocationAbbrev(); 1500 1501 Record.push_back(N->isDistinct()); 1502 Record.push_back(N->getLine()); 1503 Record.push_back(N->getColumn()); 1504 Record.push_back(VE.getMetadataID(N->getScope())); 1505 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt())); 1506 Record.push_back(N->isImplicitCode()); 1507 1508 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev); 1509 Record.clear(); 1510 } 1511 1512 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() { 1513 // Assume the column is usually under 128, and always output the inlined-at 1514 // location (it's never more expensive than building an array size 1). 1515 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1516 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG)); 1517 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1518 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1519 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1520 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1521 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1522 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1523 return Stream.EmitAbbrev(std::move(Abbv)); 1524 } 1525 1526 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N, 1527 SmallVectorImpl<uint64_t> &Record, 1528 unsigned &Abbrev) { 1529 if (!Abbrev) 1530 Abbrev = createGenericDINodeAbbrev(); 1531 1532 Record.push_back(N->isDistinct()); 1533 Record.push_back(N->getTag()); 1534 Record.push_back(0); // Per-tag version field; unused for now. 1535 1536 for (auto &I : N->operands()) 1537 Record.push_back(VE.getMetadataOrNullID(I)); 1538 1539 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev); 1540 Record.clear(); 1541 } 1542 1543 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N, 1544 SmallVectorImpl<uint64_t> &Record, 1545 unsigned Abbrev) { 1546 const uint64_t Version = 2 << 1; 1547 Record.push_back((uint64_t)N->isDistinct() | Version); 1548 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode())); 1549 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound())); 1550 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound())); 1551 Record.push_back(VE.getMetadataOrNullID(N->getRawStride())); 1552 1553 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev); 1554 Record.clear(); 1555 } 1556 1557 void ModuleBitcodeWriter::writeDIGenericSubrange( 1558 const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record, 1559 unsigned Abbrev) { 1560 Record.push_back((uint64_t)N->isDistinct()); 1561 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode())); 1562 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound())); 1563 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound())); 1564 Record.push_back(VE.getMetadataOrNullID(N->getRawStride())); 1565 1566 Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev); 1567 Record.clear(); 1568 } 1569 1570 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) { 1571 if ((int64_t)V >= 0) 1572 Vals.push_back(V << 1); 1573 else 1574 Vals.push_back((-V << 1) | 1); 1575 } 1576 1577 static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) { 1578 // We have an arbitrary precision integer value to write whose 1579 // bit width is > 64. However, in canonical unsigned integer 1580 // format it is likely that the high bits are going to be zero. 1581 // So, we only write the number of active words. 1582 unsigned NumWords = A.getActiveWords(); 1583 const uint64_t *RawData = A.getRawData(); 1584 for (unsigned i = 0; i < NumWords; i++) 1585 emitSignedInt64(Vals, RawData[i]); 1586 } 1587 1588 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N, 1589 SmallVectorImpl<uint64_t> &Record, 1590 unsigned Abbrev) { 1591 const uint64_t IsBigInt = 1 << 2; 1592 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct()); 1593 Record.push_back(N->getValue().getBitWidth()); 1594 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1595 emitWideAPInt(Record, N->getValue()); 1596 1597 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev); 1598 Record.clear(); 1599 } 1600 1601 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N, 1602 SmallVectorImpl<uint64_t> &Record, 1603 unsigned Abbrev) { 1604 Record.push_back(N->isDistinct()); 1605 Record.push_back(N->getTag()); 1606 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1607 Record.push_back(N->getSizeInBits()); 1608 Record.push_back(N->getAlignInBits()); 1609 Record.push_back(N->getEncoding()); 1610 Record.push_back(N->getFlags()); 1611 1612 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev); 1613 Record.clear(); 1614 } 1615 1616 void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N, 1617 SmallVectorImpl<uint64_t> &Record, 1618 unsigned Abbrev) { 1619 Record.push_back(N->isDistinct()); 1620 Record.push_back(N->getTag()); 1621 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1622 Record.push_back(VE.getMetadataOrNullID(N->getStringLength())); 1623 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp())); 1624 Record.push_back(N->getSizeInBits()); 1625 Record.push_back(N->getAlignInBits()); 1626 Record.push_back(N->getEncoding()); 1627 1628 Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev); 1629 Record.clear(); 1630 } 1631 1632 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N, 1633 SmallVectorImpl<uint64_t> &Record, 1634 unsigned Abbrev) { 1635 Record.push_back(N->isDistinct()); 1636 Record.push_back(N->getTag()); 1637 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1638 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1639 Record.push_back(N->getLine()); 1640 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1641 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1642 Record.push_back(N->getSizeInBits()); 1643 Record.push_back(N->getAlignInBits()); 1644 Record.push_back(N->getOffsetInBits()); 1645 Record.push_back(N->getFlags()); 1646 Record.push_back(VE.getMetadataOrNullID(N->getExtraData())); 1647 1648 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means 1649 // that there is no DWARF address space associated with DIDerivedType. 1650 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace()) 1651 Record.push_back(*DWARFAddressSpace + 1); 1652 else 1653 Record.push_back(0); 1654 1655 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev); 1656 Record.clear(); 1657 } 1658 1659 void ModuleBitcodeWriter::writeDICompositeType( 1660 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record, 1661 unsigned Abbrev) { 1662 const unsigned IsNotUsedInOldTypeRef = 0x2; 1663 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct()); 1664 Record.push_back(N->getTag()); 1665 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1666 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1667 Record.push_back(N->getLine()); 1668 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1669 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1670 Record.push_back(N->getSizeInBits()); 1671 Record.push_back(N->getAlignInBits()); 1672 Record.push_back(N->getOffsetInBits()); 1673 Record.push_back(N->getFlags()); 1674 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 1675 Record.push_back(N->getRuntimeLang()); 1676 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder())); 1677 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1678 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier())); 1679 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator())); 1680 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation())); 1681 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated())); 1682 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated())); 1683 Record.push_back(VE.getMetadataOrNullID(N->getRawRank())); 1684 1685 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev); 1686 Record.clear(); 1687 } 1688 1689 void ModuleBitcodeWriter::writeDISubroutineType( 1690 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record, 1691 unsigned Abbrev) { 1692 const unsigned HasNoOldTypeRefs = 0x2; 1693 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct()); 1694 Record.push_back(N->getFlags()); 1695 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get())); 1696 Record.push_back(N->getCC()); 1697 1698 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev); 1699 Record.clear(); 1700 } 1701 1702 void ModuleBitcodeWriter::writeDIFile(const DIFile *N, 1703 SmallVectorImpl<uint64_t> &Record, 1704 unsigned Abbrev) { 1705 Record.push_back(N->isDistinct()); 1706 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename())); 1707 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory())); 1708 if (N->getRawChecksum()) { 1709 Record.push_back(N->getRawChecksum()->Kind); 1710 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value)); 1711 } else { 1712 // Maintain backwards compatibility with the old internal representation of 1713 // CSK_None in ChecksumKind by writing nulls here when Checksum is None. 1714 Record.push_back(0); 1715 Record.push_back(VE.getMetadataOrNullID(nullptr)); 1716 } 1717 auto Source = N->getRawSource(); 1718 if (Source) 1719 Record.push_back(VE.getMetadataOrNullID(*Source)); 1720 1721 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev); 1722 Record.clear(); 1723 } 1724 1725 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N, 1726 SmallVectorImpl<uint64_t> &Record, 1727 unsigned Abbrev) { 1728 assert(N->isDistinct() && "Expected distinct compile units"); 1729 Record.push_back(/* IsDistinct */ true); 1730 Record.push_back(N->getSourceLanguage()); 1731 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1732 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer())); 1733 Record.push_back(N->isOptimized()); 1734 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags())); 1735 Record.push_back(N->getRuntimeVersion()); 1736 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename())); 1737 Record.push_back(N->getEmissionKind()); 1738 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get())); 1739 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get())); 1740 Record.push_back(/* subprograms */ 0); 1741 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get())); 1742 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get())); 1743 Record.push_back(N->getDWOId()); 1744 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get())); 1745 Record.push_back(N->getSplitDebugInlining()); 1746 Record.push_back(N->getDebugInfoForProfiling()); 1747 Record.push_back((unsigned)N->getNameTableKind()); 1748 Record.push_back(N->getRangesBaseAddress()); 1749 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot())); 1750 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK())); 1751 1752 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev); 1753 Record.clear(); 1754 } 1755 1756 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N, 1757 SmallVectorImpl<uint64_t> &Record, 1758 unsigned Abbrev) { 1759 const uint64_t HasUnitFlag = 1 << 1; 1760 const uint64_t HasSPFlagsFlag = 1 << 2; 1761 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag); 1762 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1763 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1764 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1765 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1766 Record.push_back(N->getLine()); 1767 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1768 Record.push_back(N->getScopeLine()); 1769 Record.push_back(VE.getMetadataOrNullID(N->getContainingType())); 1770 Record.push_back(N->getSPFlags()); 1771 Record.push_back(N->getVirtualIndex()); 1772 Record.push_back(N->getFlags()); 1773 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit())); 1774 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1775 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration())); 1776 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get())); 1777 Record.push_back(N->getThisAdjustment()); 1778 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get())); 1779 1780 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev); 1781 Record.clear(); 1782 } 1783 1784 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N, 1785 SmallVectorImpl<uint64_t> &Record, 1786 unsigned Abbrev) { 1787 Record.push_back(N->isDistinct()); 1788 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1789 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1790 Record.push_back(N->getLine()); 1791 Record.push_back(N->getColumn()); 1792 1793 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev); 1794 Record.clear(); 1795 } 1796 1797 void ModuleBitcodeWriter::writeDILexicalBlockFile( 1798 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record, 1799 unsigned Abbrev) { 1800 Record.push_back(N->isDistinct()); 1801 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1802 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1803 Record.push_back(N->getDiscriminator()); 1804 1805 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev); 1806 Record.clear(); 1807 } 1808 1809 void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N, 1810 SmallVectorImpl<uint64_t> &Record, 1811 unsigned Abbrev) { 1812 Record.push_back(N->isDistinct()); 1813 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1814 Record.push_back(VE.getMetadataOrNullID(N->getDecl())); 1815 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1816 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1817 Record.push_back(N->getLineNo()); 1818 1819 Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev); 1820 Record.clear(); 1821 } 1822 1823 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N, 1824 SmallVectorImpl<uint64_t> &Record, 1825 unsigned Abbrev) { 1826 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1); 1827 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1828 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1829 1830 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev); 1831 Record.clear(); 1832 } 1833 1834 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N, 1835 SmallVectorImpl<uint64_t> &Record, 1836 unsigned Abbrev) { 1837 Record.push_back(N->isDistinct()); 1838 Record.push_back(N->getMacinfoType()); 1839 Record.push_back(N->getLine()); 1840 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1841 Record.push_back(VE.getMetadataOrNullID(N->getRawValue())); 1842 1843 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev); 1844 Record.clear(); 1845 } 1846 1847 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N, 1848 SmallVectorImpl<uint64_t> &Record, 1849 unsigned Abbrev) { 1850 Record.push_back(N->isDistinct()); 1851 Record.push_back(N->getMacinfoType()); 1852 Record.push_back(N->getLine()); 1853 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1854 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 1855 1856 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev); 1857 Record.clear(); 1858 } 1859 1860 void ModuleBitcodeWriter::writeDIModule(const DIModule *N, 1861 SmallVectorImpl<uint64_t> &Record, 1862 unsigned Abbrev) { 1863 Record.push_back(N->isDistinct()); 1864 for (auto &I : N->operands()) 1865 Record.push_back(VE.getMetadataOrNullID(I)); 1866 Record.push_back(N->getLineNo()); 1867 1868 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev); 1869 Record.clear(); 1870 } 1871 1872 void ModuleBitcodeWriter::writeDITemplateTypeParameter( 1873 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record, 1874 unsigned Abbrev) { 1875 Record.push_back(N->isDistinct()); 1876 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1877 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1878 Record.push_back(N->isDefault()); 1879 1880 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev); 1881 Record.clear(); 1882 } 1883 1884 void ModuleBitcodeWriter::writeDITemplateValueParameter( 1885 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record, 1886 unsigned Abbrev) { 1887 Record.push_back(N->isDistinct()); 1888 Record.push_back(N->getTag()); 1889 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1890 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1891 Record.push_back(N->isDefault()); 1892 Record.push_back(VE.getMetadataOrNullID(N->getValue())); 1893 1894 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev); 1895 Record.clear(); 1896 } 1897 1898 void ModuleBitcodeWriter::writeDIGlobalVariable( 1899 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record, 1900 unsigned Abbrev) { 1901 const uint64_t Version = 2 << 1; 1902 Record.push_back((uint64_t)N->isDistinct() | Version); 1903 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1904 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1905 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1906 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1907 Record.push_back(N->getLine()); 1908 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1909 Record.push_back(N->isLocalToUnit()); 1910 Record.push_back(N->isDefinition()); 1911 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration())); 1912 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams())); 1913 Record.push_back(N->getAlignInBits()); 1914 1915 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev); 1916 Record.clear(); 1917 } 1918 1919 void ModuleBitcodeWriter::writeDILocalVariable( 1920 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record, 1921 unsigned Abbrev) { 1922 // In order to support all possible bitcode formats in BitcodeReader we need 1923 // to distinguish the following cases: 1924 // 1) Record has no artificial tag (Record[1]), 1925 // has no obsolete inlinedAt field (Record[9]). 1926 // In this case Record size will be 8, HasAlignment flag is false. 1927 // 2) Record has artificial tag (Record[1]), 1928 // has no obsolete inlignedAt field (Record[9]). 1929 // In this case Record size will be 9, HasAlignment flag is false. 1930 // 3) Record has both artificial tag (Record[1]) and 1931 // obsolete inlignedAt field (Record[9]). 1932 // In this case Record size will be 10, HasAlignment flag is false. 1933 // 4) Record has neither artificial tag, nor inlignedAt field, but 1934 // HasAlignment flag is true and Record[8] contains alignment value. 1935 const uint64_t HasAlignmentFlag = 1 << 1; 1936 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag); 1937 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1938 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1939 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1940 Record.push_back(N->getLine()); 1941 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1942 Record.push_back(N->getArg()); 1943 Record.push_back(N->getFlags()); 1944 Record.push_back(N->getAlignInBits()); 1945 1946 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev); 1947 Record.clear(); 1948 } 1949 1950 void ModuleBitcodeWriter::writeDILabel( 1951 const DILabel *N, SmallVectorImpl<uint64_t> &Record, 1952 unsigned Abbrev) { 1953 Record.push_back((uint64_t)N->isDistinct()); 1954 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1955 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1956 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1957 Record.push_back(N->getLine()); 1958 1959 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev); 1960 Record.clear(); 1961 } 1962 1963 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N, 1964 SmallVectorImpl<uint64_t> &Record, 1965 unsigned Abbrev) { 1966 Record.reserve(N->getElements().size() + 1); 1967 const uint64_t Version = 3 << 1; 1968 Record.push_back((uint64_t)N->isDistinct() | Version); 1969 Record.append(N->elements_begin(), N->elements_end()); 1970 1971 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev); 1972 Record.clear(); 1973 } 1974 1975 void ModuleBitcodeWriter::writeDIGlobalVariableExpression( 1976 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record, 1977 unsigned Abbrev) { 1978 Record.push_back(N->isDistinct()); 1979 Record.push_back(VE.getMetadataOrNullID(N->getVariable())); 1980 Record.push_back(VE.getMetadataOrNullID(N->getExpression())); 1981 1982 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev); 1983 Record.clear(); 1984 } 1985 1986 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N, 1987 SmallVectorImpl<uint64_t> &Record, 1988 unsigned Abbrev) { 1989 Record.push_back(N->isDistinct()); 1990 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1991 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1992 Record.push_back(N->getLine()); 1993 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName())); 1994 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName())); 1995 Record.push_back(N->getAttributes()); 1996 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1997 1998 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev); 1999 Record.clear(); 2000 } 2001 2002 void ModuleBitcodeWriter::writeDIImportedEntity( 2003 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record, 2004 unsigned Abbrev) { 2005 Record.push_back(N->isDistinct()); 2006 Record.push_back(N->getTag()); 2007 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 2008 Record.push_back(VE.getMetadataOrNullID(N->getEntity())); 2009 Record.push_back(N->getLine()); 2010 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 2011 Record.push_back(VE.getMetadataOrNullID(N->getRawFile())); 2012 2013 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev); 2014 Record.clear(); 2015 } 2016 2017 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() { 2018 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2019 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME)); 2020 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2021 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2022 return Stream.EmitAbbrev(std::move(Abbv)); 2023 } 2024 2025 void ModuleBitcodeWriter::writeNamedMetadata( 2026 SmallVectorImpl<uint64_t> &Record) { 2027 if (M.named_metadata_empty()) 2028 return; 2029 2030 unsigned Abbrev = createNamedMetadataAbbrev(); 2031 for (const NamedMDNode &NMD : M.named_metadata()) { 2032 // Write name. 2033 StringRef Str = NMD.getName(); 2034 Record.append(Str.bytes_begin(), Str.bytes_end()); 2035 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev); 2036 Record.clear(); 2037 2038 // Write named metadata operands. 2039 for (const MDNode *N : NMD.operands()) 2040 Record.push_back(VE.getMetadataID(N)); 2041 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0); 2042 Record.clear(); 2043 } 2044 } 2045 2046 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() { 2047 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2048 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS)); 2049 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings 2050 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars 2051 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2052 return Stream.EmitAbbrev(std::move(Abbv)); 2053 } 2054 2055 /// Write out a record for MDString. 2056 /// 2057 /// All the metadata strings in a metadata block are emitted in a single 2058 /// record. The sizes and strings themselves are shoved into a blob. 2059 void ModuleBitcodeWriter::writeMetadataStrings( 2060 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) { 2061 if (Strings.empty()) 2062 return; 2063 2064 // Start the record with the number of strings. 2065 Record.push_back(bitc::METADATA_STRINGS); 2066 Record.push_back(Strings.size()); 2067 2068 // Emit the sizes of the strings in the blob. 2069 SmallString<256> Blob; 2070 { 2071 BitstreamWriter W(Blob); 2072 for (const Metadata *MD : Strings) 2073 W.EmitVBR(cast<MDString>(MD)->getLength(), 6); 2074 W.FlushToWord(); 2075 } 2076 2077 // Add the offset to the strings to the record. 2078 Record.push_back(Blob.size()); 2079 2080 // Add the strings to the blob. 2081 for (const Metadata *MD : Strings) 2082 Blob.append(cast<MDString>(MD)->getString()); 2083 2084 // Emit the final record. 2085 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob); 2086 Record.clear(); 2087 } 2088 2089 // Generates an enum to use as an index in the Abbrev array of Metadata record. 2090 enum MetadataAbbrev : unsigned { 2091 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID, 2092 #include "llvm/IR/Metadata.def" 2093 LastPlusOne 2094 }; 2095 2096 void ModuleBitcodeWriter::writeMetadataRecords( 2097 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record, 2098 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) { 2099 if (MDs.empty()) 2100 return; 2101 2102 // Initialize MDNode abbreviations. 2103 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0; 2104 #include "llvm/IR/Metadata.def" 2105 2106 for (const Metadata *MD : MDs) { 2107 if (IndexPos) 2108 IndexPos->push_back(Stream.GetCurrentBitNo()); 2109 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 2110 assert(N->isResolved() && "Expected forward references to be resolved"); 2111 2112 switch (N->getMetadataID()) { 2113 default: 2114 llvm_unreachable("Invalid MDNode subclass"); 2115 #define HANDLE_MDNODE_LEAF(CLASS) \ 2116 case Metadata::CLASS##Kind: \ 2117 if (MDAbbrevs) \ 2118 write##CLASS(cast<CLASS>(N), Record, \ 2119 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \ 2120 else \ 2121 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \ 2122 continue; 2123 #include "llvm/IR/Metadata.def" 2124 } 2125 } 2126 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record); 2127 } 2128 } 2129 2130 void ModuleBitcodeWriter::writeModuleMetadata() { 2131 if (!VE.hasMDs() && M.named_metadata_empty()) 2132 return; 2133 2134 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4); 2135 SmallVector<uint64_t, 64> Record; 2136 2137 // Emit all abbrevs upfront, so that the reader can jump in the middle of the 2138 // block and load any metadata. 2139 std::vector<unsigned> MDAbbrevs; 2140 2141 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne); 2142 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev(); 2143 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] = 2144 createGenericDINodeAbbrev(); 2145 2146 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2147 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET)); 2148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2150 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 2151 2152 Abbv = std::make_shared<BitCodeAbbrev>(); 2153 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX)); 2154 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2155 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 2156 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 2157 2158 // Emit MDStrings together upfront. 2159 writeMetadataStrings(VE.getMDStrings(), Record); 2160 2161 // We only emit an index for the metadata record if we have more than a given 2162 // (naive) threshold of metadatas, otherwise it is not worth it. 2163 if (VE.getNonMDStrings().size() > IndexThreshold) { 2164 // Write a placeholder value in for the offset of the metadata index, 2165 // which is written after the records, so that it can include 2166 // the offset of each entry. The placeholder offset will be 2167 // updated after all records are emitted. 2168 uint64_t Vals[] = {0, 0}; 2169 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev); 2170 } 2171 2172 // Compute and save the bit offset to the current position, which will be 2173 // patched when we emit the index later. We can simply subtract the 64-bit 2174 // fixed size from the current bit number to get the location to backpatch. 2175 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo(); 2176 2177 // This index will contain the bitpos for each individual record. 2178 std::vector<uint64_t> IndexPos; 2179 IndexPos.reserve(VE.getNonMDStrings().size()); 2180 2181 // Write all the records 2182 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos); 2183 2184 if (VE.getNonMDStrings().size() > IndexThreshold) { 2185 // Now that we have emitted all the records we will emit the index. But 2186 // first 2187 // backpatch the forward reference so that the reader can skip the records 2188 // efficiently. 2189 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64, 2190 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos); 2191 2192 // Delta encode the index. 2193 uint64_t PreviousValue = IndexOffsetRecordBitPos; 2194 for (auto &Elt : IndexPos) { 2195 auto EltDelta = Elt - PreviousValue; 2196 PreviousValue = Elt; 2197 Elt = EltDelta; 2198 } 2199 // Emit the index record. 2200 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev); 2201 IndexPos.clear(); 2202 } 2203 2204 // Write the named metadata now. 2205 writeNamedMetadata(Record); 2206 2207 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) { 2208 SmallVector<uint64_t, 4> Record; 2209 Record.push_back(VE.getValueID(&GO)); 2210 pushGlobalMetadataAttachment(Record, GO); 2211 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record); 2212 }; 2213 for (const Function &F : M) 2214 if (F.isDeclaration() && F.hasMetadata()) 2215 AddDeclAttachedMetadata(F); 2216 // FIXME: Only store metadata for declarations here, and move data for global 2217 // variable definitions to a separate block (PR28134). 2218 for (const GlobalVariable &GV : M.globals()) 2219 if (GV.hasMetadata()) 2220 AddDeclAttachedMetadata(GV); 2221 2222 Stream.ExitBlock(); 2223 } 2224 2225 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) { 2226 if (!VE.hasMDs()) 2227 return; 2228 2229 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 2230 SmallVector<uint64_t, 64> Record; 2231 writeMetadataStrings(VE.getMDStrings(), Record); 2232 writeMetadataRecords(VE.getNonMDStrings(), Record); 2233 Stream.ExitBlock(); 2234 } 2235 2236 void ModuleBitcodeWriter::pushGlobalMetadataAttachment( 2237 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) { 2238 // [n x [id, mdnode]] 2239 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2240 GO.getAllMetadata(MDs); 2241 for (const auto &I : MDs) { 2242 Record.push_back(I.first); 2243 Record.push_back(VE.getMetadataID(I.second)); 2244 } 2245 } 2246 2247 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) { 2248 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); 2249 2250 SmallVector<uint64_t, 64> Record; 2251 2252 if (F.hasMetadata()) { 2253 pushGlobalMetadataAttachment(Record, F); 2254 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 2255 Record.clear(); 2256 } 2257 2258 // Write metadata attachments 2259 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] 2260 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2261 for (const BasicBlock &BB : F) 2262 for (const Instruction &I : BB) { 2263 MDs.clear(); 2264 I.getAllMetadataOtherThanDebugLoc(MDs); 2265 2266 // If no metadata, ignore instruction. 2267 if (MDs.empty()) continue; 2268 2269 Record.push_back(VE.getInstructionID(&I)); 2270 2271 for (unsigned i = 0, e = MDs.size(); i != e; ++i) { 2272 Record.push_back(MDs[i].first); 2273 Record.push_back(VE.getMetadataID(MDs[i].second)); 2274 } 2275 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 2276 Record.clear(); 2277 } 2278 2279 Stream.ExitBlock(); 2280 } 2281 2282 void ModuleBitcodeWriter::writeModuleMetadataKinds() { 2283 SmallVector<uint64_t, 64> Record; 2284 2285 // Write metadata kinds 2286 // METADATA_KIND - [n x [id, name]] 2287 SmallVector<StringRef, 8> Names; 2288 M.getMDKindNames(Names); 2289 2290 if (Names.empty()) return; 2291 2292 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3); 2293 2294 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) { 2295 Record.push_back(MDKindID); 2296 StringRef KName = Names[MDKindID]; 2297 Record.append(KName.begin(), KName.end()); 2298 2299 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); 2300 Record.clear(); 2301 } 2302 2303 Stream.ExitBlock(); 2304 } 2305 2306 void ModuleBitcodeWriter::writeOperandBundleTags() { 2307 // Write metadata kinds 2308 // 2309 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG 2310 // 2311 // OPERAND_BUNDLE_TAG - [strchr x N] 2312 2313 SmallVector<StringRef, 8> Tags; 2314 M.getOperandBundleTags(Tags); 2315 2316 if (Tags.empty()) 2317 return; 2318 2319 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3); 2320 2321 SmallVector<uint64_t, 64> Record; 2322 2323 for (auto Tag : Tags) { 2324 Record.append(Tag.begin(), Tag.end()); 2325 2326 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0); 2327 Record.clear(); 2328 } 2329 2330 Stream.ExitBlock(); 2331 } 2332 2333 void ModuleBitcodeWriter::writeSyncScopeNames() { 2334 SmallVector<StringRef, 8> SSNs; 2335 M.getContext().getSyncScopeNames(SSNs); 2336 if (SSNs.empty()) 2337 return; 2338 2339 Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2); 2340 2341 SmallVector<uint64_t, 64> Record; 2342 for (auto SSN : SSNs) { 2343 Record.append(SSN.begin(), SSN.end()); 2344 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0); 2345 Record.clear(); 2346 } 2347 2348 Stream.ExitBlock(); 2349 } 2350 2351 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal, 2352 bool isGlobal) { 2353 if (FirstVal == LastVal) return; 2354 2355 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); 2356 2357 unsigned AggregateAbbrev = 0; 2358 unsigned String8Abbrev = 0; 2359 unsigned CString7Abbrev = 0; 2360 unsigned CString6Abbrev = 0; 2361 // If this is a constant pool for the module, emit module-specific abbrevs. 2362 if (isGlobal) { 2363 // Abbrev for CST_CODE_AGGREGATE. 2364 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2365 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE)); 2366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1))); 2368 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 2369 2370 // Abbrev for CST_CODE_STRING. 2371 Abbv = std::make_shared<BitCodeAbbrev>(); 2372 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING)); 2373 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2374 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2375 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 2376 // Abbrev for CST_CODE_CSTRING. 2377 Abbv = std::make_shared<BitCodeAbbrev>(); 2378 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 2379 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2380 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 2381 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 2382 // Abbrev for CST_CODE_CSTRING. 2383 Abbv = std::make_shared<BitCodeAbbrev>(); 2384 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 2385 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2386 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2387 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 2388 } 2389 2390 SmallVector<uint64_t, 64> Record; 2391 2392 const ValueEnumerator::ValueList &Vals = VE.getValues(); 2393 Type *LastTy = nullptr; 2394 for (unsigned i = FirstVal; i != LastVal; ++i) { 2395 const Value *V = Vals[i].first; 2396 // If we need to switch types, do so now. 2397 if (V->getType() != LastTy) { 2398 LastTy = V->getType(); 2399 Record.push_back(VE.getTypeID(LastTy)); 2400 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record, 2401 CONSTANTS_SETTYPE_ABBREV); 2402 Record.clear(); 2403 } 2404 2405 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 2406 Record.push_back(unsigned(IA->hasSideEffects()) | 2407 unsigned(IA->isAlignStack()) << 1 | 2408 unsigned(IA->getDialect()&1) << 2); 2409 2410 // Add the asm string. 2411 const std::string &AsmStr = IA->getAsmString(); 2412 Record.push_back(AsmStr.size()); 2413 Record.append(AsmStr.begin(), AsmStr.end()); 2414 2415 // Add the constraint string. 2416 const std::string &ConstraintStr = IA->getConstraintString(); 2417 Record.push_back(ConstraintStr.size()); 2418 Record.append(ConstraintStr.begin(), ConstraintStr.end()); 2419 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record); 2420 Record.clear(); 2421 continue; 2422 } 2423 const Constant *C = cast<Constant>(V); 2424 unsigned Code = -1U; 2425 unsigned AbbrevToUse = 0; 2426 if (C->isNullValue()) { 2427 Code = bitc::CST_CODE_NULL; 2428 } else if (isa<PoisonValue>(C)) { 2429 Code = bitc::CST_CODE_POISON; 2430 } else if (isa<UndefValue>(C)) { 2431 Code = bitc::CST_CODE_UNDEF; 2432 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 2433 if (IV->getBitWidth() <= 64) { 2434 uint64_t V = IV->getSExtValue(); 2435 emitSignedInt64(Record, V); 2436 Code = bitc::CST_CODE_INTEGER; 2437 AbbrevToUse = CONSTANTS_INTEGER_ABBREV; 2438 } else { // Wide integers, > 64 bits in size. 2439 emitWideAPInt(Record, IV->getValue()); 2440 Code = bitc::CST_CODE_WIDE_INTEGER; 2441 } 2442 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 2443 Code = bitc::CST_CODE_FLOAT; 2444 Type *Ty = CFP->getType(); 2445 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || 2446 Ty->isDoubleTy()) { 2447 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue()); 2448 } else if (Ty->isX86_FP80Ty()) { 2449 // api needed to prevent premature destruction 2450 // bits are not in the same order as a normal i80 APInt, compensate. 2451 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2452 const uint64_t *p = api.getRawData(); 2453 Record.push_back((p[1] << 48) | (p[0] >> 16)); 2454 Record.push_back(p[0] & 0xffffLL); 2455 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) { 2456 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2457 const uint64_t *p = api.getRawData(); 2458 Record.push_back(p[0]); 2459 Record.push_back(p[1]); 2460 } else { 2461 assert(0 && "Unknown FP type!"); 2462 } 2463 } else if (isa<ConstantDataSequential>(C) && 2464 cast<ConstantDataSequential>(C)->isString()) { 2465 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C); 2466 // Emit constant strings specially. 2467 unsigned NumElts = Str->getNumElements(); 2468 // If this is a null-terminated string, use the denser CSTRING encoding. 2469 if (Str->isCString()) { 2470 Code = bitc::CST_CODE_CSTRING; 2471 --NumElts; // Don't encode the null, which isn't allowed by char6. 2472 } else { 2473 Code = bitc::CST_CODE_STRING; 2474 AbbrevToUse = String8Abbrev; 2475 } 2476 bool isCStr7 = Code == bitc::CST_CODE_CSTRING; 2477 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; 2478 for (unsigned i = 0; i != NumElts; ++i) { 2479 unsigned char V = Str->getElementAsInteger(i); 2480 Record.push_back(V); 2481 isCStr7 &= (V & 128) == 0; 2482 if (isCStrChar6) 2483 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 2484 } 2485 2486 if (isCStrChar6) 2487 AbbrevToUse = CString6Abbrev; 2488 else if (isCStr7) 2489 AbbrevToUse = CString7Abbrev; 2490 } else if (const ConstantDataSequential *CDS = 2491 dyn_cast<ConstantDataSequential>(C)) { 2492 Code = bitc::CST_CODE_DATA; 2493 Type *EltTy = CDS->getElementType(); 2494 if (isa<IntegerType>(EltTy)) { 2495 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 2496 Record.push_back(CDS->getElementAsInteger(i)); 2497 } else { 2498 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 2499 Record.push_back( 2500 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue()); 2501 } 2502 } else if (isa<ConstantAggregate>(C)) { 2503 Code = bitc::CST_CODE_AGGREGATE; 2504 for (const Value *Op : C->operands()) 2505 Record.push_back(VE.getValueID(Op)); 2506 AbbrevToUse = AggregateAbbrev; 2507 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 2508 switch (CE->getOpcode()) { 2509 default: 2510 if (Instruction::isCast(CE->getOpcode())) { 2511 Code = bitc::CST_CODE_CE_CAST; 2512 Record.push_back(getEncodedCastOpcode(CE->getOpcode())); 2513 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2514 Record.push_back(VE.getValueID(C->getOperand(0))); 2515 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev; 2516 } else { 2517 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 2518 Code = bitc::CST_CODE_CE_BINOP; 2519 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode())); 2520 Record.push_back(VE.getValueID(C->getOperand(0))); 2521 Record.push_back(VE.getValueID(C->getOperand(1))); 2522 uint64_t Flags = getOptimizationFlags(CE); 2523 if (Flags != 0) 2524 Record.push_back(Flags); 2525 } 2526 break; 2527 case Instruction::FNeg: { 2528 assert(CE->getNumOperands() == 1 && "Unknown constant expr!"); 2529 Code = bitc::CST_CODE_CE_UNOP; 2530 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode())); 2531 Record.push_back(VE.getValueID(C->getOperand(0))); 2532 uint64_t Flags = getOptimizationFlags(CE); 2533 if (Flags != 0) 2534 Record.push_back(Flags); 2535 break; 2536 } 2537 case Instruction::GetElementPtr: { 2538 Code = bitc::CST_CODE_CE_GEP; 2539 const auto *GO = cast<GEPOperator>(C); 2540 Record.push_back(VE.getTypeID(GO->getSourceElementType())); 2541 if (Optional<unsigned> Idx = GO->getInRangeIndex()) { 2542 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX; 2543 Record.push_back((*Idx << 1) | GO->isInBounds()); 2544 } else if (GO->isInBounds()) 2545 Code = bitc::CST_CODE_CE_INBOUNDS_GEP; 2546 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 2547 Record.push_back(VE.getTypeID(C->getOperand(i)->getType())); 2548 Record.push_back(VE.getValueID(C->getOperand(i))); 2549 } 2550 break; 2551 } 2552 case Instruction::Select: 2553 Code = bitc::CST_CODE_CE_SELECT; 2554 Record.push_back(VE.getValueID(C->getOperand(0))); 2555 Record.push_back(VE.getValueID(C->getOperand(1))); 2556 Record.push_back(VE.getValueID(C->getOperand(2))); 2557 break; 2558 case Instruction::ExtractElement: 2559 Code = bitc::CST_CODE_CE_EXTRACTELT; 2560 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2561 Record.push_back(VE.getValueID(C->getOperand(0))); 2562 Record.push_back(VE.getTypeID(C->getOperand(1)->getType())); 2563 Record.push_back(VE.getValueID(C->getOperand(1))); 2564 break; 2565 case Instruction::InsertElement: 2566 Code = bitc::CST_CODE_CE_INSERTELT; 2567 Record.push_back(VE.getValueID(C->getOperand(0))); 2568 Record.push_back(VE.getValueID(C->getOperand(1))); 2569 Record.push_back(VE.getTypeID(C->getOperand(2)->getType())); 2570 Record.push_back(VE.getValueID(C->getOperand(2))); 2571 break; 2572 case Instruction::ShuffleVector: 2573 // If the return type and argument types are the same, this is a 2574 // standard shufflevector instruction. If the types are different, 2575 // then the shuffle is widening or truncating the input vectors, and 2576 // the argument type must also be encoded. 2577 if (C->getType() == C->getOperand(0)->getType()) { 2578 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 2579 } else { 2580 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 2581 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2582 } 2583 Record.push_back(VE.getValueID(C->getOperand(0))); 2584 Record.push_back(VE.getValueID(C->getOperand(1))); 2585 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode())); 2586 break; 2587 case Instruction::ICmp: 2588 case Instruction::FCmp: 2589 Code = bitc::CST_CODE_CE_CMP; 2590 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2591 Record.push_back(VE.getValueID(C->getOperand(0))); 2592 Record.push_back(VE.getValueID(C->getOperand(1))); 2593 Record.push_back(CE->getPredicate()); 2594 break; 2595 } 2596 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) { 2597 Code = bitc::CST_CODE_BLOCKADDRESS; 2598 Record.push_back(VE.getTypeID(BA->getFunction()->getType())); 2599 Record.push_back(VE.getValueID(BA->getFunction())); 2600 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock())); 2601 } else { 2602 #ifndef NDEBUG 2603 C->dump(); 2604 #endif 2605 llvm_unreachable("Unknown constant!"); 2606 } 2607 Stream.EmitRecord(Code, Record, AbbrevToUse); 2608 Record.clear(); 2609 } 2610 2611 Stream.ExitBlock(); 2612 } 2613 2614 void ModuleBitcodeWriter::writeModuleConstants() { 2615 const ValueEnumerator::ValueList &Vals = VE.getValues(); 2616 2617 // Find the first constant to emit, which is the first non-globalvalue value. 2618 // We know globalvalues have been emitted by WriteModuleInfo. 2619 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 2620 if (!isa<GlobalValue>(Vals[i].first)) { 2621 writeConstants(i, Vals.size(), true); 2622 return; 2623 } 2624 } 2625 } 2626 2627 /// pushValueAndType - The file has to encode both the value and type id for 2628 /// many values, because we need to know what type to create for forward 2629 /// references. However, most operands are not forward references, so this type 2630 /// field is not needed. 2631 /// 2632 /// This function adds V's value ID to Vals. If the value ID is higher than the 2633 /// instruction ID, then it is a forward reference, and it also includes the 2634 /// type ID. The value ID that is written is encoded relative to the InstID. 2635 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID, 2636 SmallVectorImpl<unsigned> &Vals) { 2637 unsigned ValID = VE.getValueID(V); 2638 // Make encoding relative to the InstID. 2639 Vals.push_back(InstID - ValID); 2640 if (ValID >= InstID) { 2641 Vals.push_back(VE.getTypeID(V->getType())); 2642 return true; 2643 } 2644 return false; 2645 } 2646 2647 void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS, 2648 unsigned InstID) { 2649 SmallVector<unsigned, 64> Record; 2650 LLVMContext &C = CS.getContext(); 2651 2652 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) { 2653 const auto &Bundle = CS.getOperandBundleAt(i); 2654 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName())); 2655 2656 for (auto &Input : Bundle.Inputs) 2657 pushValueAndType(Input, InstID, Record); 2658 2659 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record); 2660 Record.clear(); 2661 } 2662 } 2663 2664 /// pushValue - Like pushValueAndType, but where the type of the value is 2665 /// omitted (perhaps it was already encoded in an earlier operand). 2666 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID, 2667 SmallVectorImpl<unsigned> &Vals) { 2668 unsigned ValID = VE.getValueID(V); 2669 Vals.push_back(InstID - ValID); 2670 } 2671 2672 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID, 2673 SmallVectorImpl<uint64_t> &Vals) { 2674 unsigned ValID = VE.getValueID(V); 2675 int64_t diff = ((int32_t)InstID - (int32_t)ValID); 2676 emitSignedInt64(Vals, diff); 2677 } 2678 2679 /// WriteInstruction - Emit an instruction to the specified stream. 2680 void ModuleBitcodeWriter::writeInstruction(const Instruction &I, 2681 unsigned InstID, 2682 SmallVectorImpl<unsigned> &Vals) { 2683 unsigned Code = 0; 2684 unsigned AbbrevToUse = 0; 2685 VE.setInstructionID(&I); 2686 switch (I.getOpcode()) { 2687 default: 2688 if (Instruction::isCast(I.getOpcode())) { 2689 Code = bitc::FUNC_CODE_INST_CAST; 2690 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2691 AbbrevToUse = FUNCTION_INST_CAST_ABBREV; 2692 Vals.push_back(VE.getTypeID(I.getType())); 2693 Vals.push_back(getEncodedCastOpcode(I.getOpcode())); 2694 } else { 2695 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 2696 Code = bitc::FUNC_CODE_INST_BINOP; 2697 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2698 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV; 2699 pushValue(I.getOperand(1), InstID, Vals); 2700 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode())); 2701 uint64_t Flags = getOptimizationFlags(&I); 2702 if (Flags != 0) { 2703 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV) 2704 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV; 2705 Vals.push_back(Flags); 2706 } 2707 } 2708 break; 2709 case Instruction::FNeg: { 2710 Code = bitc::FUNC_CODE_INST_UNOP; 2711 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2712 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV; 2713 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode())); 2714 uint64_t Flags = getOptimizationFlags(&I); 2715 if (Flags != 0) { 2716 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV) 2717 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV; 2718 Vals.push_back(Flags); 2719 } 2720 break; 2721 } 2722 case Instruction::GetElementPtr: { 2723 Code = bitc::FUNC_CODE_INST_GEP; 2724 AbbrevToUse = FUNCTION_INST_GEP_ABBREV; 2725 auto &GEPInst = cast<GetElementPtrInst>(I); 2726 Vals.push_back(GEPInst.isInBounds()); 2727 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType())); 2728 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 2729 pushValueAndType(I.getOperand(i), InstID, Vals); 2730 break; 2731 } 2732 case Instruction::ExtractValue: { 2733 Code = bitc::FUNC_CODE_INST_EXTRACTVAL; 2734 pushValueAndType(I.getOperand(0), InstID, Vals); 2735 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I); 2736 Vals.append(EVI->idx_begin(), EVI->idx_end()); 2737 break; 2738 } 2739 case Instruction::InsertValue: { 2740 Code = bitc::FUNC_CODE_INST_INSERTVAL; 2741 pushValueAndType(I.getOperand(0), InstID, Vals); 2742 pushValueAndType(I.getOperand(1), InstID, Vals); 2743 const InsertValueInst *IVI = cast<InsertValueInst>(&I); 2744 Vals.append(IVI->idx_begin(), IVI->idx_end()); 2745 break; 2746 } 2747 case Instruction::Select: { 2748 Code = bitc::FUNC_CODE_INST_VSELECT; 2749 pushValueAndType(I.getOperand(1), InstID, Vals); 2750 pushValue(I.getOperand(2), InstID, Vals); 2751 pushValueAndType(I.getOperand(0), InstID, Vals); 2752 uint64_t Flags = getOptimizationFlags(&I); 2753 if (Flags != 0) 2754 Vals.push_back(Flags); 2755 break; 2756 } 2757 case Instruction::ExtractElement: 2758 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 2759 pushValueAndType(I.getOperand(0), InstID, Vals); 2760 pushValueAndType(I.getOperand(1), InstID, Vals); 2761 break; 2762 case Instruction::InsertElement: 2763 Code = bitc::FUNC_CODE_INST_INSERTELT; 2764 pushValueAndType(I.getOperand(0), InstID, Vals); 2765 pushValue(I.getOperand(1), InstID, Vals); 2766 pushValueAndType(I.getOperand(2), InstID, Vals); 2767 break; 2768 case Instruction::ShuffleVector: 2769 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 2770 pushValueAndType(I.getOperand(0), InstID, Vals); 2771 pushValue(I.getOperand(1), InstID, Vals); 2772 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID, 2773 Vals); 2774 break; 2775 case Instruction::ICmp: 2776 case Instruction::FCmp: { 2777 // compare returning Int1Ty or vector of Int1Ty 2778 Code = bitc::FUNC_CODE_INST_CMP2; 2779 pushValueAndType(I.getOperand(0), InstID, Vals); 2780 pushValue(I.getOperand(1), InstID, Vals); 2781 Vals.push_back(cast<CmpInst>(I).getPredicate()); 2782 uint64_t Flags = getOptimizationFlags(&I); 2783 if (Flags != 0) 2784 Vals.push_back(Flags); 2785 break; 2786 } 2787 2788 case Instruction::Ret: 2789 { 2790 Code = bitc::FUNC_CODE_INST_RET; 2791 unsigned NumOperands = I.getNumOperands(); 2792 if (NumOperands == 0) 2793 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV; 2794 else if (NumOperands == 1) { 2795 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2796 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV; 2797 } else { 2798 for (unsigned i = 0, e = NumOperands; i != e; ++i) 2799 pushValueAndType(I.getOperand(i), InstID, Vals); 2800 } 2801 } 2802 break; 2803 case Instruction::Br: 2804 { 2805 Code = bitc::FUNC_CODE_INST_BR; 2806 const BranchInst &II = cast<BranchInst>(I); 2807 Vals.push_back(VE.getValueID(II.getSuccessor(0))); 2808 if (II.isConditional()) { 2809 Vals.push_back(VE.getValueID(II.getSuccessor(1))); 2810 pushValue(II.getCondition(), InstID, Vals); 2811 } 2812 } 2813 break; 2814 case Instruction::Switch: 2815 { 2816 Code = bitc::FUNC_CODE_INST_SWITCH; 2817 const SwitchInst &SI = cast<SwitchInst>(I); 2818 Vals.push_back(VE.getTypeID(SI.getCondition()->getType())); 2819 pushValue(SI.getCondition(), InstID, Vals); 2820 Vals.push_back(VE.getValueID(SI.getDefaultDest())); 2821 for (auto Case : SI.cases()) { 2822 Vals.push_back(VE.getValueID(Case.getCaseValue())); 2823 Vals.push_back(VE.getValueID(Case.getCaseSuccessor())); 2824 } 2825 } 2826 break; 2827 case Instruction::IndirectBr: 2828 Code = bitc::FUNC_CODE_INST_INDIRECTBR; 2829 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 2830 // Encode the address operand as relative, but not the basic blocks. 2831 pushValue(I.getOperand(0), InstID, Vals); 2832 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) 2833 Vals.push_back(VE.getValueID(I.getOperand(i))); 2834 break; 2835 2836 case Instruction::Invoke: { 2837 const InvokeInst *II = cast<InvokeInst>(&I); 2838 const Value *Callee = II->getCalledOperand(); 2839 FunctionType *FTy = II->getFunctionType(); 2840 2841 if (II->hasOperandBundles()) 2842 writeOperandBundles(*II, InstID); 2843 2844 Code = bitc::FUNC_CODE_INST_INVOKE; 2845 2846 Vals.push_back(VE.getAttributeListID(II->getAttributes())); 2847 Vals.push_back(II->getCallingConv() | 1 << 13); 2848 Vals.push_back(VE.getValueID(II->getNormalDest())); 2849 Vals.push_back(VE.getValueID(II->getUnwindDest())); 2850 Vals.push_back(VE.getTypeID(FTy)); 2851 pushValueAndType(Callee, InstID, Vals); 2852 2853 // Emit value #'s for the fixed parameters. 2854 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2855 pushValue(I.getOperand(i), InstID, Vals); // fixed param. 2856 2857 // Emit type/value pairs for varargs params. 2858 if (FTy->isVarArg()) { 2859 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands(); 2860 i != e; ++i) 2861 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg 2862 } 2863 break; 2864 } 2865 case Instruction::Resume: 2866 Code = bitc::FUNC_CODE_INST_RESUME; 2867 pushValueAndType(I.getOperand(0), InstID, Vals); 2868 break; 2869 case Instruction::CleanupRet: { 2870 Code = bitc::FUNC_CODE_INST_CLEANUPRET; 2871 const auto &CRI = cast<CleanupReturnInst>(I); 2872 pushValue(CRI.getCleanupPad(), InstID, Vals); 2873 if (CRI.hasUnwindDest()) 2874 Vals.push_back(VE.getValueID(CRI.getUnwindDest())); 2875 break; 2876 } 2877 case Instruction::CatchRet: { 2878 Code = bitc::FUNC_CODE_INST_CATCHRET; 2879 const auto &CRI = cast<CatchReturnInst>(I); 2880 pushValue(CRI.getCatchPad(), InstID, Vals); 2881 Vals.push_back(VE.getValueID(CRI.getSuccessor())); 2882 break; 2883 } 2884 case Instruction::CleanupPad: 2885 case Instruction::CatchPad: { 2886 const auto &FuncletPad = cast<FuncletPadInst>(I); 2887 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD 2888 : bitc::FUNC_CODE_INST_CLEANUPPAD; 2889 pushValue(FuncletPad.getParentPad(), InstID, Vals); 2890 2891 unsigned NumArgOperands = FuncletPad.getNumArgOperands(); 2892 Vals.push_back(NumArgOperands); 2893 for (unsigned Op = 0; Op != NumArgOperands; ++Op) 2894 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals); 2895 break; 2896 } 2897 case Instruction::CatchSwitch: { 2898 Code = bitc::FUNC_CODE_INST_CATCHSWITCH; 2899 const auto &CatchSwitch = cast<CatchSwitchInst>(I); 2900 2901 pushValue(CatchSwitch.getParentPad(), InstID, Vals); 2902 2903 unsigned NumHandlers = CatchSwitch.getNumHandlers(); 2904 Vals.push_back(NumHandlers); 2905 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers()) 2906 Vals.push_back(VE.getValueID(CatchPadBB)); 2907 2908 if (CatchSwitch.hasUnwindDest()) 2909 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest())); 2910 break; 2911 } 2912 case Instruction::CallBr: { 2913 const CallBrInst *CBI = cast<CallBrInst>(&I); 2914 const Value *Callee = CBI->getCalledOperand(); 2915 FunctionType *FTy = CBI->getFunctionType(); 2916 2917 if (CBI->hasOperandBundles()) 2918 writeOperandBundles(*CBI, InstID); 2919 2920 Code = bitc::FUNC_CODE_INST_CALLBR; 2921 2922 Vals.push_back(VE.getAttributeListID(CBI->getAttributes())); 2923 2924 Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV | 2925 1 << bitc::CALL_EXPLICIT_TYPE); 2926 2927 Vals.push_back(VE.getValueID(CBI->getDefaultDest())); 2928 Vals.push_back(CBI->getNumIndirectDests()); 2929 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) 2930 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i))); 2931 2932 Vals.push_back(VE.getTypeID(FTy)); 2933 pushValueAndType(Callee, InstID, Vals); 2934 2935 // Emit value #'s for the fixed parameters. 2936 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2937 pushValue(I.getOperand(i), InstID, Vals); // fixed param. 2938 2939 // Emit type/value pairs for varargs params. 2940 if (FTy->isVarArg()) { 2941 for (unsigned i = FTy->getNumParams(), e = CBI->getNumArgOperands(); 2942 i != e; ++i) 2943 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg 2944 } 2945 break; 2946 } 2947 case Instruction::Unreachable: 2948 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 2949 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV; 2950 break; 2951 2952 case Instruction::PHI: { 2953 const PHINode &PN = cast<PHINode>(I); 2954 Code = bitc::FUNC_CODE_INST_PHI; 2955 // With the newer instruction encoding, forward references could give 2956 // negative valued IDs. This is most common for PHIs, so we use 2957 // signed VBRs. 2958 SmallVector<uint64_t, 128> Vals64; 2959 Vals64.push_back(VE.getTypeID(PN.getType())); 2960 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 2961 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64); 2962 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i))); 2963 } 2964 2965 uint64_t Flags = getOptimizationFlags(&I); 2966 if (Flags != 0) 2967 Vals64.push_back(Flags); 2968 2969 // Emit a Vals64 vector and exit. 2970 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 2971 Vals64.clear(); 2972 return; 2973 } 2974 2975 case Instruction::LandingPad: { 2976 const LandingPadInst &LP = cast<LandingPadInst>(I); 2977 Code = bitc::FUNC_CODE_INST_LANDINGPAD; 2978 Vals.push_back(VE.getTypeID(LP.getType())); 2979 Vals.push_back(LP.isCleanup()); 2980 Vals.push_back(LP.getNumClauses()); 2981 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) { 2982 if (LP.isCatch(I)) 2983 Vals.push_back(LandingPadInst::Catch); 2984 else 2985 Vals.push_back(LandingPadInst::Filter); 2986 pushValueAndType(LP.getClause(I), InstID, Vals); 2987 } 2988 break; 2989 } 2990 2991 case Instruction::Alloca: { 2992 Code = bitc::FUNC_CODE_INST_ALLOCA; 2993 const AllocaInst &AI = cast<AllocaInst>(I); 2994 Vals.push_back(VE.getTypeID(AI.getAllocatedType())); 2995 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 2996 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 2997 using APV = AllocaPackedValues; 2998 unsigned Record = 0; 2999 Bitfield::set<APV::Align>(Record, getEncodedAlign(AI.getAlign())); 3000 Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca()); 3001 Bitfield::set<APV::ExplicitType>(Record, true); 3002 Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError()); 3003 Vals.push_back(Record); 3004 break; 3005 } 3006 3007 case Instruction::Load: 3008 if (cast<LoadInst>(I).isAtomic()) { 3009 Code = bitc::FUNC_CODE_INST_LOADATOMIC; 3010 pushValueAndType(I.getOperand(0), InstID, Vals); 3011 } else { 3012 Code = bitc::FUNC_CODE_INST_LOAD; 3013 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr 3014 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV; 3015 } 3016 Vals.push_back(VE.getTypeID(I.getType())); 3017 Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign())); 3018 Vals.push_back(cast<LoadInst>(I).isVolatile()); 3019 if (cast<LoadInst>(I).isAtomic()) { 3020 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering())); 3021 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID())); 3022 } 3023 break; 3024 case Instruction::Store: 3025 if (cast<StoreInst>(I).isAtomic()) 3026 Code = bitc::FUNC_CODE_INST_STOREATOMIC; 3027 else 3028 Code = bitc::FUNC_CODE_INST_STORE; 3029 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr 3030 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val 3031 Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign())); 3032 Vals.push_back(cast<StoreInst>(I).isVolatile()); 3033 if (cast<StoreInst>(I).isAtomic()) { 3034 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering())); 3035 Vals.push_back( 3036 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID())); 3037 } 3038 break; 3039 case Instruction::AtomicCmpXchg: 3040 Code = bitc::FUNC_CODE_INST_CMPXCHG; 3041 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 3042 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp. 3043 pushValue(I.getOperand(2), InstID, Vals); // newval. 3044 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile()); 3045 Vals.push_back( 3046 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering())); 3047 Vals.push_back( 3048 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID())); 3049 Vals.push_back( 3050 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering())); 3051 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak()); 3052 break; 3053 case Instruction::AtomicRMW: 3054 Code = bitc::FUNC_CODE_INST_ATOMICRMW; 3055 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 3056 pushValue(I.getOperand(1), InstID, Vals); // val. 3057 Vals.push_back( 3058 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation())); 3059 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile()); 3060 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering())); 3061 Vals.push_back( 3062 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID())); 3063 break; 3064 case Instruction::Fence: 3065 Code = bitc::FUNC_CODE_INST_FENCE; 3066 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering())); 3067 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID())); 3068 break; 3069 case Instruction::Call: { 3070 const CallInst &CI = cast<CallInst>(I); 3071 FunctionType *FTy = CI.getFunctionType(); 3072 3073 if (CI.hasOperandBundles()) 3074 writeOperandBundles(CI, InstID); 3075 3076 Code = bitc::FUNC_CODE_INST_CALL; 3077 3078 Vals.push_back(VE.getAttributeListID(CI.getAttributes())); 3079 3080 unsigned Flags = getOptimizationFlags(&I); 3081 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV | 3082 unsigned(CI.isTailCall()) << bitc::CALL_TAIL | 3083 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL | 3084 1 << bitc::CALL_EXPLICIT_TYPE | 3085 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL | 3086 unsigned(Flags != 0) << bitc::CALL_FMF); 3087 if (Flags != 0) 3088 Vals.push_back(Flags); 3089 3090 Vals.push_back(VE.getTypeID(FTy)); 3091 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee 3092 3093 // Emit value #'s for the fixed parameters. 3094 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 3095 // Check for labels (can happen with asm labels). 3096 if (FTy->getParamType(i)->isLabelTy()) 3097 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); 3098 else 3099 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param. 3100 } 3101 3102 // Emit type/value pairs for varargs params. 3103 if (FTy->isVarArg()) { 3104 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands(); 3105 i != e; ++i) 3106 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs 3107 } 3108 break; 3109 } 3110 case Instruction::VAArg: 3111 Code = bitc::FUNC_CODE_INST_VAARG; 3112 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty 3113 pushValue(I.getOperand(0), InstID, Vals); // valist. 3114 Vals.push_back(VE.getTypeID(I.getType())); // restype. 3115 break; 3116 case Instruction::Freeze: 3117 Code = bitc::FUNC_CODE_INST_FREEZE; 3118 pushValueAndType(I.getOperand(0), InstID, Vals); 3119 break; 3120 } 3121 3122 Stream.EmitRecord(Code, Vals, AbbrevToUse); 3123 Vals.clear(); 3124 } 3125 3126 /// Write a GlobalValue VST to the module. The purpose of this data structure is 3127 /// to allow clients to efficiently find the function body. 3128 void ModuleBitcodeWriter::writeGlobalValueSymbolTable( 3129 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) { 3130 // Get the offset of the VST we are writing, and backpatch it into 3131 // the VST forward declaration record. 3132 uint64_t VSTOffset = Stream.GetCurrentBitNo(); 3133 // The BitcodeStartBit was the stream offset of the identification block. 3134 VSTOffset -= bitcodeStartBit(); 3135 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned"); 3136 // Note that we add 1 here because the offset is relative to one word 3137 // before the start of the identification block, which was historically 3138 // always the start of the regular bitcode header. 3139 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1); 3140 3141 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 3142 3143 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3144 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY)); 3145 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 3146 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset 3147 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3148 3149 for (const Function &F : M) { 3150 uint64_t Record[2]; 3151 3152 if (F.isDeclaration()) 3153 continue; 3154 3155 Record[0] = VE.getValueID(&F); 3156 3157 // Save the word offset of the function (from the start of the 3158 // actual bitcode written to the stream). 3159 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit(); 3160 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned"); 3161 // Note that we add 1 here because the offset is relative to one word 3162 // before the start of the identification block, which was historically 3163 // always the start of the regular bitcode header. 3164 Record[1] = BitcodeIndex / 32 + 1; 3165 3166 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev); 3167 } 3168 3169 Stream.ExitBlock(); 3170 } 3171 3172 /// Emit names for arguments, instructions and basic blocks in a function. 3173 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable( 3174 const ValueSymbolTable &VST) { 3175 if (VST.empty()) 3176 return; 3177 3178 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 3179 3180 // FIXME: Set up the abbrev, we know how many values there are! 3181 // FIXME: We know if the type names can use 7-bit ascii. 3182 SmallVector<uint64_t, 64> NameVals; 3183 3184 for (const ValueName &Name : VST) { 3185 // Figure out the encoding to use for the name. 3186 StringEncoding Bits = getStringEncoding(Name.getKey()); 3187 3188 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 3189 NameVals.push_back(VE.getValueID(Name.getValue())); 3190 3191 // VST_CODE_ENTRY: [valueid, namechar x N] 3192 // VST_CODE_BBENTRY: [bbid, namechar x N] 3193 unsigned Code; 3194 if (isa<BasicBlock>(Name.getValue())) { 3195 Code = bitc::VST_CODE_BBENTRY; 3196 if (Bits == SE_Char6) 3197 AbbrevToUse = VST_BBENTRY_6_ABBREV; 3198 } else { 3199 Code = bitc::VST_CODE_ENTRY; 3200 if (Bits == SE_Char6) 3201 AbbrevToUse = VST_ENTRY_6_ABBREV; 3202 else if (Bits == SE_Fixed7) 3203 AbbrevToUse = VST_ENTRY_7_ABBREV; 3204 } 3205 3206 for (const auto P : Name.getKey()) 3207 NameVals.push_back((unsigned char)P); 3208 3209 // Emit the finished record. 3210 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 3211 NameVals.clear(); 3212 } 3213 3214 Stream.ExitBlock(); 3215 } 3216 3217 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) { 3218 assert(Order.Shuffle.size() >= 2 && "Shuffle too small"); 3219 unsigned Code; 3220 if (isa<BasicBlock>(Order.V)) 3221 Code = bitc::USELIST_CODE_BB; 3222 else 3223 Code = bitc::USELIST_CODE_DEFAULT; 3224 3225 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end()); 3226 Record.push_back(VE.getValueID(Order.V)); 3227 Stream.EmitRecord(Code, Record); 3228 } 3229 3230 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) { 3231 assert(VE.shouldPreserveUseListOrder() && 3232 "Expected to be preserving use-list order"); 3233 3234 auto hasMore = [&]() { 3235 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F; 3236 }; 3237 if (!hasMore()) 3238 // Nothing to do. 3239 return; 3240 3241 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3); 3242 while (hasMore()) { 3243 writeUseList(std::move(VE.UseListOrders.back())); 3244 VE.UseListOrders.pop_back(); 3245 } 3246 Stream.ExitBlock(); 3247 } 3248 3249 /// Emit a function body to the module stream. 3250 void ModuleBitcodeWriter::writeFunction( 3251 const Function &F, 3252 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) { 3253 // Save the bitcode index of the start of this function block for recording 3254 // in the VST. 3255 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo(); 3256 3257 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 3258 VE.incorporateFunction(F); 3259 3260 SmallVector<unsigned, 64> Vals; 3261 3262 // Emit the number of basic blocks, so the reader can create them ahead of 3263 // time. 3264 Vals.push_back(VE.getBasicBlocks().size()); 3265 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 3266 Vals.clear(); 3267 3268 // If there are function-local constants, emit them now. 3269 unsigned CstStart, CstEnd; 3270 VE.getFunctionConstantRange(CstStart, CstEnd); 3271 writeConstants(CstStart, CstEnd, false); 3272 3273 // If there is function-local metadata, emit it now. 3274 writeFunctionMetadata(F); 3275 3276 // Keep a running idea of what the instruction ID is. 3277 unsigned InstID = CstEnd; 3278 3279 bool NeedsMetadataAttachment = F.hasMetadata(); 3280 3281 DILocation *LastDL = nullptr; 3282 // Finally, emit all the instructions, in order. 3283 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 3284 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 3285 I != E; ++I) { 3286 writeInstruction(*I, InstID, Vals); 3287 3288 if (!I->getType()->isVoidTy()) 3289 ++InstID; 3290 3291 // If the instruction has metadata, write a metadata attachment later. 3292 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc(); 3293 3294 // If the instruction has a debug location, emit it. 3295 DILocation *DL = I->getDebugLoc(); 3296 if (!DL) 3297 continue; 3298 3299 if (DL == LastDL) { 3300 // Just repeat the same debug loc as last time. 3301 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals); 3302 continue; 3303 } 3304 3305 Vals.push_back(DL->getLine()); 3306 Vals.push_back(DL->getColumn()); 3307 Vals.push_back(VE.getMetadataOrNullID(DL->getScope())); 3308 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt())); 3309 Vals.push_back(DL->isImplicitCode()); 3310 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals); 3311 Vals.clear(); 3312 3313 LastDL = DL; 3314 } 3315 3316 // Emit names for all the instructions etc. 3317 if (auto *Symtab = F.getValueSymbolTable()) 3318 writeFunctionLevelValueSymbolTable(*Symtab); 3319 3320 if (NeedsMetadataAttachment) 3321 writeFunctionMetadataAttachment(F); 3322 if (VE.shouldPreserveUseListOrder()) 3323 writeUseListBlock(&F); 3324 VE.purgeFunction(); 3325 Stream.ExitBlock(); 3326 } 3327 3328 // Emit blockinfo, which defines the standard abbreviations etc. 3329 void ModuleBitcodeWriter::writeBlockInfo() { 3330 // We only want to emit block info records for blocks that have multiple 3331 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. 3332 // Other blocks can define their abbrevs inline. 3333 Stream.EnterBlockInfoBlock(); 3334 3335 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings. 3336 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3337 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 3338 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 3341 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3342 VST_ENTRY_8_ABBREV) 3343 llvm_unreachable("Unexpected abbrev ordering!"); 3344 } 3345 3346 { // 7-bit fixed width VST_CODE_ENTRY strings. 3347 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3348 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 3349 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 3352 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3353 VST_ENTRY_7_ABBREV) 3354 llvm_unreachable("Unexpected abbrev ordering!"); 3355 } 3356 { // 6-bit char6 VST_CODE_ENTRY strings. 3357 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3358 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 3359 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3360 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3361 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3362 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3363 VST_ENTRY_6_ABBREV) 3364 llvm_unreachable("Unexpected abbrev ordering!"); 3365 } 3366 { // 6-bit char6 VST_CODE_BBENTRY strings. 3367 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3368 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY)); 3369 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3370 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3371 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3372 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3373 VST_BBENTRY_6_ABBREV) 3374 llvm_unreachable("Unexpected abbrev ordering!"); 3375 } 3376 3377 { // SETTYPE abbrev for CONSTANTS_BLOCK. 3378 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3379 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); 3380 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3381 VE.computeBitsRequiredForTypeIndicies())); 3382 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3383 CONSTANTS_SETTYPE_ABBREV) 3384 llvm_unreachable("Unexpected abbrev ordering!"); 3385 } 3386 3387 { // INTEGER abbrev for CONSTANTS_BLOCK. 3388 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3389 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); 3390 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3391 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3392 CONSTANTS_INTEGER_ABBREV) 3393 llvm_unreachable("Unexpected abbrev ordering!"); 3394 } 3395 3396 { // CE_CAST abbrev for CONSTANTS_BLOCK. 3397 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3398 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); 3399 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc 3400 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid 3401 VE.computeBitsRequiredForTypeIndicies())); 3402 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 3403 3404 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3405 CONSTANTS_CE_CAST_Abbrev) 3406 llvm_unreachable("Unexpected abbrev ordering!"); 3407 } 3408 { // NULL abbrev for CONSTANTS_BLOCK. 3409 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3410 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL)); 3411 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3412 CONSTANTS_NULL_Abbrev) 3413 llvm_unreachable("Unexpected abbrev ordering!"); 3414 } 3415 3416 // FIXME: This should only use space for first class types! 3417 3418 { // INST_LOAD abbrev for FUNCTION_BLOCK. 3419 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3420 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); 3421 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr 3422 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3423 VE.computeBitsRequiredForTypeIndicies())); 3424 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align 3425 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile 3426 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3427 FUNCTION_INST_LOAD_ABBREV) 3428 llvm_unreachable("Unexpected abbrev ordering!"); 3429 } 3430 { // INST_UNOP abbrev for FUNCTION_BLOCK. 3431 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3432 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP)); 3433 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3434 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3435 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3436 FUNCTION_INST_UNOP_ABBREV) 3437 llvm_unreachable("Unexpected abbrev ordering!"); 3438 } 3439 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK. 3440 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3441 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP)); 3442 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3443 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3444 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags 3445 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3446 FUNCTION_INST_UNOP_FLAGS_ABBREV) 3447 llvm_unreachable("Unexpected abbrev ordering!"); 3448 } 3449 { // INST_BINOP abbrev for FUNCTION_BLOCK. 3450 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3451 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 3452 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3453 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 3454 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3455 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3456 FUNCTION_INST_BINOP_ABBREV) 3457 llvm_unreachable("Unexpected abbrev ordering!"); 3458 } 3459 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK. 3460 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3461 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 3462 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3463 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 3464 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3465 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags 3466 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3467 FUNCTION_INST_BINOP_FLAGS_ABBREV) 3468 llvm_unreachable("Unexpected abbrev ordering!"); 3469 } 3470 { // INST_CAST abbrev for FUNCTION_BLOCK. 3471 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3472 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 3473 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 3474 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3475 VE.computeBitsRequiredForTypeIndicies())); 3476 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3477 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3478 FUNCTION_INST_CAST_ABBREV) 3479 llvm_unreachable("Unexpected abbrev ordering!"); 3480 } 3481 3482 { // INST_RET abbrev for FUNCTION_BLOCK. 3483 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3484 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 3485 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3486 FUNCTION_INST_RET_VOID_ABBREV) 3487 llvm_unreachable("Unexpected abbrev ordering!"); 3488 } 3489 { // INST_RET abbrev for FUNCTION_BLOCK. 3490 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3491 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 3492 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID 3493 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3494 FUNCTION_INST_RET_VAL_ABBREV) 3495 llvm_unreachable("Unexpected abbrev ordering!"); 3496 } 3497 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK. 3498 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3499 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE)); 3500 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3501 FUNCTION_INST_UNREACHABLE_ABBREV) 3502 llvm_unreachable("Unexpected abbrev ordering!"); 3503 } 3504 { 3505 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3506 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP)); 3507 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 3508 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3509 Log2_32_Ceil(VE.getTypes().size() + 1))); 3510 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3511 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 3512 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3513 FUNCTION_INST_GEP_ABBREV) 3514 llvm_unreachable("Unexpected abbrev ordering!"); 3515 } 3516 3517 Stream.ExitBlock(); 3518 } 3519 3520 /// Write the module path strings, currently only used when generating 3521 /// a combined index file. 3522 void IndexBitcodeWriter::writeModStrings() { 3523 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3); 3524 3525 // TODO: See which abbrev sizes we actually need to emit 3526 3527 // 8-bit fixed-width MST_ENTRY strings. 3528 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3529 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3530 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3531 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3532 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 3533 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv)); 3534 3535 // 7-bit fixed width MST_ENTRY strings. 3536 Abbv = std::make_shared<BitCodeAbbrev>(); 3537 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3538 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3539 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3540 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 3541 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv)); 3542 3543 // 6-bit char6 MST_ENTRY strings. 3544 Abbv = std::make_shared<BitCodeAbbrev>(); 3545 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3546 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3547 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3548 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3549 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv)); 3550 3551 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY. 3552 Abbv = std::make_shared<BitCodeAbbrev>(); 3553 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH)); 3554 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3555 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3556 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3557 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3558 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3559 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv)); 3560 3561 SmallVector<unsigned, 64> Vals; 3562 forEachModule( 3563 [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) { 3564 StringRef Key = MPSE.getKey(); 3565 const auto &Value = MPSE.getValue(); 3566 StringEncoding Bits = getStringEncoding(Key); 3567 unsigned AbbrevToUse = Abbrev8Bit; 3568 if (Bits == SE_Char6) 3569 AbbrevToUse = Abbrev6Bit; 3570 else if (Bits == SE_Fixed7) 3571 AbbrevToUse = Abbrev7Bit; 3572 3573 Vals.push_back(Value.first); 3574 Vals.append(Key.begin(), Key.end()); 3575 3576 // Emit the finished record. 3577 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse); 3578 3579 // Emit an optional hash for the module now 3580 const auto &Hash = Value.second; 3581 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) { 3582 Vals.assign(Hash.begin(), Hash.end()); 3583 // Emit the hash record. 3584 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash); 3585 } 3586 3587 Vals.clear(); 3588 }); 3589 Stream.ExitBlock(); 3590 } 3591 3592 /// Write the function type metadata related records that need to appear before 3593 /// a function summary entry (whether per-module or combined). 3594 template <typename Fn> 3595 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream, 3596 FunctionSummary *FS, 3597 Fn GetValueID) { 3598 if (!FS->type_tests().empty()) 3599 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests()); 3600 3601 SmallVector<uint64_t, 64> Record; 3602 3603 auto WriteVFuncIdVec = [&](uint64_t Ty, 3604 ArrayRef<FunctionSummary::VFuncId> VFs) { 3605 if (VFs.empty()) 3606 return; 3607 Record.clear(); 3608 for (auto &VF : VFs) { 3609 Record.push_back(VF.GUID); 3610 Record.push_back(VF.Offset); 3611 } 3612 Stream.EmitRecord(Ty, Record); 3613 }; 3614 3615 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS, 3616 FS->type_test_assume_vcalls()); 3617 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS, 3618 FS->type_checked_load_vcalls()); 3619 3620 auto WriteConstVCallVec = [&](uint64_t Ty, 3621 ArrayRef<FunctionSummary::ConstVCall> VCs) { 3622 for (auto &VC : VCs) { 3623 Record.clear(); 3624 Record.push_back(VC.VFunc.GUID); 3625 Record.push_back(VC.VFunc.Offset); 3626 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end()); 3627 Stream.EmitRecord(Ty, Record); 3628 } 3629 }; 3630 3631 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL, 3632 FS->type_test_assume_const_vcalls()); 3633 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL, 3634 FS->type_checked_load_const_vcalls()); 3635 3636 auto WriteRange = [&](ConstantRange Range) { 3637 Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth); 3638 assert(Range.getLower().getNumWords() == 1); 3639 assert(Range.getUpper().getNumWords() == 1); 3640 emitSignedInt64(Record, *Range.getLower().getRawData()); 3641 emitSignedInt64(Record, *Range.getUpper().getRawData()); 3642 }; 3643 3644 if (!FS->paramAccesses().empty()) { 3645 Record.clear(); 3646 for (auto &Arg : FS->paramAccesses()) { 3647 size_t UndoSize = Record.size(); 3648 Record.push_back(Arg.ParamNo); 3649 WriteRange(Arg.Use); 3650 Record.push_back(Arg.Calls.size()); 3651 for (auto &Call : Arg.Calls) { 3652 Record.push_back(Call.ParamNo); 3653 Optional<unsigned> ValueID = GetValueID(Call.Callee); 3654 if (!ValueID) { 3655 // If ValueID is unknown we can't drop just this call, we must drop 3656 // entire parameter. 3657 Record.resize(UndoSize); 3658 break; 3659 } 3660 Record.push_back(*ValueID); 3661 WriteRange(Call.Offsets); 3662 } 3663 } 3664 if (!Record.empty()) 3665 Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record); 3666 } 3667 } 3668 3669 /// Collect type IDs from type tests used by function. 3670 static void 3671 getReferencedTypeIds(FunctionSummary *FS, 3672 std::set<GlobalValue::GUID> &ReferencedTypeIds) { 3673 if (!FS->type_tests().empty()) 3674 for (auto &TT : FS->type_tests()) 3675 ReferencedTypeIds.insert(TT); 3676 3677 auto GetReferencedTypesFromVFuncIdVec = 3678 [&](ArrayRef<FunctionSummary::VFuncId> VFs) { 3679 for (auto &VF : VFs) 3680 ReferencedTypeIds.insert(VF.GUID); 3681 }; 3682 3683 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls()); 3684 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls()); 3685 3686 auto GetReferencedTypesFromConstVCallVec = 3687 [&](ArrayRef<FunctionSummary::ConstVCall> VCs) { 3688 for (auto &VC : VCs) 3689 ReferencedTypeIds.insert(VC.VFunc.GUID); 3690 }; 3691 3692 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls()); 3693 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls()); 3694 } 3695 3696 static void writeWholeProgramDevirtResolutionByArg( 3697 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args, 3698 const WholeProgramDevirtResolution::ByArg &ByArg) { 3699 NameVals.push_back(args.size()); 3700 NameVals.insert(NameVals.end(), args.begin(), args.end()); 3701 3702 NameVals.push_back(ByArg.TheKind); 3703 NameVals.push_back(ByArg.Info); 3704 NameVals.push_back(ByArg.Byte); 3705 NameVals.push_back(ByArg.Bit); 3706 } 3707 3708 static void writeWholeProgramDevirtResolution( 3709 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder, 3710 uint64_t Id, const WholeProgramDevirtResolution &Wpd) { 3711 NameVals.push_back(Id); 3712 3713 NameVals.push_back(Wpd.TheKind); 3714 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName)); 3715 NameVals.push_back(Wpd.SingleImplName.size()); 3716 3717 NameVals.push_back(Wpd.ResByArg.size()); 3718 for (auto &A : Wpd.ResByArg) 3719 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second); 3720 } 3721 3722 static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals, 3723 StringTableBuilder &StrtabBuilder, 3724 const std::string &Id, 3725 const TypeIdSummary &Summary) { 3726 NameVals.push_back(StrtabBuilder.add(Id)); 3727 NameVals.push_back(Id.size()); 3728 3729 NameVals.push_back(Summary.TTRes.TheKind); 3730 NameVals.push_back(Summary.TTRes.SizeM1BitWidth); 3731 NameVals.push_back(Summary.TTRes.AlignLog2); 3732 NameVals.push_back(Summary.TTRes.SizeM1); 3733 NameVals.push_back(Summary.TTRes.BitMask); 3734 NameVals.push_back(Summary.TTRes.InlineBits); 3735 3736 for (auto &W : Summary.WPDRes) 3737 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first, 3738 W.second); 3739 } 3740 3741 static void writeTypeIdCompatibleVtableSummaryRecord( 3742 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder, 3743 const std::string &Id, const TypeIdCompatibleVtableInfo &Summary, 3744 ValueEnumerator &VE) { 3745 NameVals.push_back(StrtabBuilder.add(Id)); 3746 NameVals.push_back(Id.size()); 3747 3748 for (auto &P : Summary) { 3749 NameVals.push_back(P.AddressPointOffset); 3750 NameVals.push_back(VE.getValueID(P.VTableVI.getValue())); 3751 } 3752 } 3753 3754 // Helper to emit a single function summary record. 3755 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord( 3756 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary, 3757 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev, 3758 const Function &F) { 3759 NameVals.push_back(ValueID); 3760 3761 FunctionSummary *FS = cast<FunctionSummary>(Summary); 3762 3763 writeFunctionTypeMetadataRecords( 3764 Stream, FS, [&](const ValueInfo &VI) -> Optional<unsigned> { 3765 return {VE.getValueID(VI.getValue())}; 3766 }); 3767 3768 auto SpecialRefCnts = FS->specialRefCounts(); 3769 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags())); 3770 NameVals.push_back(FS->instCount()); 3771 NameVals.push_back(getEncodedFFlags(FS->fflags())); 3772 NameVals.push_back(FS->refs().size()); 3773 NameVals.push_back(SpecialRefCnts.first); // rorefcnt 3774 NameVals.push_back(SpecialRefCnts.second); // worefcnt 3775 3776 for (auto &RI : FS->refs()) 3777 NameVals.push_back(VE.getValueID(RI.getValue())); 3778 3779 bool HasProfileData = 3780 F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None; 3781 for (auto &ECI : FS->calls()) { 3782 NameVals.push_back(getValueId(ECI.first)); 3783 if (HasProfileData) 3784 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness)); 3785 else if (WriteRelBFToSummary) 3786 NameVals.push_back(ECI.second.RelBlockFreq); 3787 } 3788 3789 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev); 3790 unsigned Code = 3791 (HasProfileData ? bitc::FS_PERMODULE_PROFILE 3792 : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF 3793 : bitc::FS_PERMODULE)); 3794 3795 // Emit the finished record. 3796 Stream.EmitRecord(Code, NameVals, FSAbbrev); 3797 NameVals.clear(); 3798 } 3799 3800 // Collect the global value references in the given variable's initializer, 3801 // and emit them in a summary record. 3802 void ModuleBitcodeWriterBase::writeModuleLevelReferences( 3803 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals, 3804 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) { 3805 auto VI = Index->getValueInfo(V.getGUID()); 3806 if (!VI || VI.getSummaryList().empty()) { 3807 // Only declarations should not have a summary (a declaration might however 3808 // have a summary if the def was in module level asm). 3809 assert(V.isDeclaration()); 3810 return; 3811 } 3812 auto *Summary = VI.getSummaryList()[0].get(); 3813 NameVals.push_back(VE.getValueID(&V)); 3814 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary); 3815 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags())); 3816 NameVals.push_back(getEncodedGVarFlags(VS->varflags())); 3817 3818 auto VTableFuncs = VS->vTableFuncs(); 3819 if (!VTableFuncs.empty()) 3820 NameVals.push_back(VS->refs().size()); 3821 3822 unsigned SizeBeforeRefs = NameVals.size(); 3823 for (auto &RI : VS->refs()) 3824 NameVals.push_back(VE.getValueID(RI.getValue())); 3825 // Sort the refs for determinism output, the vector returned by FS->refs() has 3826 // been initialized from a DenseSet. 3827 llvm::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end()); 3828 3829 if (VTableFuncs.empty()) 3830 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals, 3831 FSModRefsAbbrev); 3832 else { 3833 // VTableFuncs pairs should already be sorted by offset. 3834 for (auto &P : VTableFuncs) { 3835 NameVals.push_back(VE.getValueID(P.FuncVI.getValue())); 3836 NameVals.push_back(P.VTableOffset); 3837 } 3838 3839 Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals, 3840 FSModVTableRefsAbbrev); 3841 } 3842 NameVals.clear(); 3843 } 3844 3845 /// Emit the per-module summary section alongside the rest of 3846 /// the module's bitcode. 3847 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() { 3848 // By default we compile with ThinLTO if the module has a summary, but the 3849 // client can request full LTO with a module flag. 3850 bool IsThinLTO = true; 3851 if (auto *MD = 3852 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO"))) 3853 IsThinLTO = MD->getZExtValue(); 3854 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID 3855 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID, 3856 4); 3857 3858 Stream.EmitRecord( 3859 bitc::FS_VERSION, 3860 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion}); 3861 3862 // Write the index flags. 3863 uint64_t Flags = 0; 3864 // Bits 1-3 are set only in the combined index, skip them. 3865 if (Index->enableSplitLTOUnit()) 3866 Flags |= 0x8; 3867 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags}); 3868 3869 if (Index->begin() == Index->end()) { 3870 Stream.ExitBlock(); 3871 return; 3872 } 3873 3874 for (const auto &GVI : valueIds()) { 3875 Stream.EmitRecord(bitc::FS_VALUE_GUID, 3876 ArrayRef<uint64_t>{GVI.second, GVI.first}); 3877 } 3878 3879 // Abbrev for FS_PERMODULE_PROFILE. 3880 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3881 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE)); 3882 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3883 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3884 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 3885 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 3886 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3887 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 3888 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 3889 // numrefs x valueid, n x (valueid, hotness) 3890 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3891 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3892 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3893 3894 // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF. 3895 Abbv = std::make_shared<BitCodeAbbrev>(); 3896 if (WriteRelBFToSummary) 3897 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF)); 3898 else 3899 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE)); 3900 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3901 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3902 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 3903 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 3904 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3905 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 3906 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 3907 // numrefs x valueid, n x (valueid [, rel_block_freq]) 3908 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3909 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3910 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3911 3912 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS. 3913 Abbv = std::make_shared<BitCodeAbbrev>(); 3914 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS)); 3915 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3916 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3917 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 3918 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3919 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3920 3921 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS. 3922 Abbv = std::make_shared<BitCodeAbbrev>(); 3923 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS)); 3924 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3925 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3926 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3927 // numrefs x valueid, n x (valueid , offset) 3928 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3929 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3930 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3931 3932 // Abbrev for FS_ALIAS. 3933 Abbv = std::make_shared<BitCodeAbbrev>(); 3934 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS)); 3935 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3936 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3937 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3938 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3939 3940 // Abbrev for FS_TYPE_ID_METADATA 3941 Abbv = std::make_shared<BitCodeAbbrev>(); 3942 Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA)); 3943 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index 3944 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length 3945 // n x (valueid , offset) 3946 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3947 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3948 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3949 3950 SmallVector<uint64_t, 64> NameVals; 3951 // Iterate over the list of functions instead of the Index to 3952 // ensure the ordering is stable. 3953 for (const Function &F : M) { 3954 // Summary emission does not support anonymous functions, they have to 3955 // renamed using the anonymous function renaming pass. 3956 if (!F.hasName()) 3957 report_fatal_error("Unexpected anonymous function when writing summary"); 3958 3959 ValueInfo VI = Index->getValueInfo(F.getGUID()); 3960 if (!VI || VI.getSummaryList().empty()) { 3961 // Only declarations should not have a summary (a declaration might 3962 // however have a summary if the def was in module level asm). 3963 assert(F.isDeclaration()); 3964 continue; 3965 } 3966 auto *Summary = VI.getSummaryList()[0].get(); 3967 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F), 3968 FSCallsAbbrev, FSCallsProfileAbbrev, F); 3969 } 3970 3971 // Capture references from GlobalVariable initializers, which are outside 3972 // of a function scope. 3973 for (const GlobalVariable &G : M.globals()) 3974 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev, 3975 FSModVTableRefsAbbrev); 3976 3977 for (const GlobalAlias &A : M.aliases()) { 3978 auto *Aliasee = A.getBaseObject(); 3979 if (!Aliasee->hasName()) 3980 // Nameless function don't have an entry in the summary, skip it. 3981 continue; 3982 auto AliasId = VE.getValueID(&A); 3983 auto AliaseeId = VE.getValueID(Aliasee); 3984 NameVals.push_back(AliasId); 3985 auto *Summary = Index->getGlobalValueSummary(A); 3986 AliasSummary *AS = cast<AliasSummary>(Summary); 3987 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags())); 3988 NameVals.push_back(AliaseeId); 3989 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev); 3990 NameVals.clear(); 3991 } 3992 3993 for (auto &S : Index->typeIdCompatibleVtableMap()) { 3994 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first, 3995 S.second, VE); 3996 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals, 3997 TypeIdCompatibleVtableAbbrev); 3998 NameVals.clear(); 3999 } 4000 4001 Stream.EmitRecord(bitc::FS_BLOCK_COUNT, 4002 ArrayRef<uint64_t>{Index->getBlockCount()}); 4003 4004 Stream.ExitBlock(); 4005 } 4006 4007 /// Emit the combined summary section into the combined index file. 4008 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() { 4009 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3); 4010 Stream.EmitRecord( 4011 bitc::FS_VERSION, 4012 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion}); 4013 4014 // Write the index flags. 4015 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()}); 4016 4017 for (const auto &GVI : valueIds()) { 4018 Stream.EmitRecord(bitc::FS_VALUE_GUID, 4019 ArrayRef<uint64_t>{GVI.second, GVI.first}); 4020 } 4021 4022 // Abbrev for FS_COMBINED. 4023 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4024 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED)); 4025 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4026 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 4027 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4028 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 4029 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 4030 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount 4031 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 4032 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 4033 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 4034 // numrefs x valueid, n x (valueid) 4035 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4036 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4037 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4038 4039 // Abbrev for FS_COMBINED_PROFILE. 4040 Abbv = std::make_shared<BitCodeAbbrev>(); 4041 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE)); 4042 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4043 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 4044 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4045 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 4046 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 4047 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount 4048 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 4049 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 4050 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 4051 // numrefs x valueid, n x (valueid, hotness) 4052 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4053 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4054 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4055 4056 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS. 4057 Abbv = std::make_shared<BitCodeAbbrev>(); 4058 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS)); 4059 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4060 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 4061 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4062 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 4063 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 4064 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4065 4066 // Abbrev for FS_COMBINED_ALIAS. 4067 Abbv = std::make_shared<BitCodeAbbrev>(); 4068 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS)); 4069 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4070 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 4071 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 4072 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 4073 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4074 4075 // The aliases are emitted as a post-pass, and will point to the value 4076 // id of the aliasee. Save them in a vector for post-processing. 4077 SmallVector<AliasSummary *, 64> Aliases; 4078 4079 // Save the value id for each summary for alias emission. 4080 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap; 4081 4082 SmallVector<uint64_t, 64> NameVals; 4083 4084 // Set that will be populated during call to writeFunctionTypeMetadataRecords 4085 // with the type ids referenced by this index file. 4086 std::set<GlobalValue::GUID> ReferencedTypeIds; 4087 4088 // For local linkage, we also emit the original name separately 4089 // immediately after the record. 4090 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) { 4091 if (!GlobalValue::isLocalLinkage(S.linkage())) 4092 return; 4093 NameVals.push_back(S.getOriginalName()); 4094 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals); 4095 NameVals.clear(); 4096 }; 4097 4098 std::set<GlobalValue::GUID> DefOrUseGUIDs; 4099 forEachSummary([&](GVInfo I, bool IsAliasee) { 4100 GlobalValueSummary *S = I.second; 4101 assert(S); 4102 DefOrUseGUIDs.insert(I.first); 4103 for (const ValueInfo &VI : S->refs()) 4104 DefOrUseGUIDs.insert(VI.getGUID()); 4105 4106 auto ValueId = getValueId(I.first); 4107 assert(ValueId); 4108 SummaryToValueIdMap[S] = *ValueId; 4109 4110 // If this is invoked for an aliasee, we want to record the above 4111 // mapping, but then not emit a summary entry (if the aliasee is 4112 // to be imported, we will invoke this separately with IsAliasee=false). 4113 if (IsAliasee) 4114 return; 4115 4116 if (auto *AS = dyn_cast<AliasSummary>(S)) { 4117 // Will process aliases as a post-pass because the reader wants all 4118 // global to be loaded first. 4119 Aliases.push_back(AS); 4120 return; 4121 } 4122 4123 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) { 4124 NameVals.push_back(*ValueId); 4125 NameVals.push_back(Index.getModuleId(VS->modulePath())); 4126 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags())); 4127 NameVals.push_back(getEncodedGVarFlags(VS->varflags())); 4128 for (auto &RI : VS->refs()) { 4129 auto RefValueId = getValueId(RI.getGUID()); 4130 if (!RefValueId) 4131 continue; 4132 NameVals.push_back(*RefValueId); 4133 } 4134 4135 // Emit the finished record. 4136 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals, 4137 FSModRefsAbbrev); 4138 NameVals.clear(); 4139 MaybeEmitOriginalName(*S); 4140 return; 4141 } 4142 4143 auto GetValueId = [&](const ValueInfo &VI) -> Optional<unsigned> { 4144 GlobalValue::GUID GUID = VI.getGUID(); 4145 Optional<unsigned> CallValueId = getValueId(GUID); 4146 if (CallValueId) 4147 return CallValueId; 4148 // For SamplePGO, the indirect call targets for local functions will 4149 // have its original name annotated in profile. We try to find the 4150 // corresponding PGOFuncName as the GUID. 4151 GUID = Index.getGUIDFromOriginalID(GUID); 4152 if (!GUID) 4153 return None; 4154 CallValueId = getValueId(GUID); 4155 if (!CallValueId) 4156 return None; 4157 // The mapping from OriginalId to GUID may return a GUID 4158 // that corresponds to a static variable. Filter it out here. 4159 // This can happen when 4160 // 1) There is a call to a library function which does not have 4161 // a CallValidId; 4162 // 2) There is a static variable with the OriginalGUID identical 4163 // to the GUID of the library function in 1); 4164 // When this happens, the logic for SamplePGO kicks in and 4165 // the static variable in 2) will be found, which needs to be 4166 // filtered out. 4167 auto *GVSum = Index.getGlobalValueSummary(GUID, false); 4168 if (GVSum && GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind) 4169 return None; 4170 return CallValueId; 4171 }; 4172 4173 auto *FS = cast<FunctionSummary>(S); 4174 writeFunctionTypeMetadataRecords(Stream, FS, GetValueId); 4175 getReferencedTypeIds(FS, ReferencedTypeIds); 4176 4177 NameVals.push_back(*ValueId); 4178 NameVals.push_back(Index.getModuleId(FS->modulePath())); 4179 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags())); 4180 NameVals.push_back(FS->instCount()); 4181 NameVals.push_back(getEncodedFFlags(FS->fflags())); 4182 NameVals.push_back(FS->entryCount()); 4183 4184 // Fill in below 4185 NameVals.push_back(0); // numrefs 4186 NameVals.push_back(0); // rorefcnt 4187 NameVals.push_back(0); // worefcnt 4188 4189 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0; 4190 for (auto &RI : FS->refs()) { 4191 auto RefValueId = getValueId(RI.getGUID()); 4192 if (!RefValueId) 4193 continue; 4194 NameVals.push_back(*RefValueId); 4195 if (RI.isReadOnly()) 4196 RORefCnt++; 4197 else if (RI.isWriteOnly()) 4198 WORefCnt++; 4199 Count++; 4200 } 4201 NameVals[6] = Count; 4202 NameVals[7] = RORefCnt; 4203 NameVals[8] = WORefCnt; 4204 4205 bool HasProfileData = false; 4206 for (auto &EI : FS->calls()) { 4207 HasProfileData |= 4208 EI.second.getHotness() != CalleeInfo::HotnessType::Unknown; 4209 if (HasProfileData) 4210 break; 4211 } 4212 4213 for (auto &EI : FS->calls()) { 4214 // If this GUID doesn't have a value id, it doesn't have a function 4215 // summary and we don't need to record any calls to it. 4216 Optional<unsigned> CallValueId = GetValueId(EI.first); 4217 if (!CallValueId) 4218 continue; 4219 NameVals.push_back(*CallValueId); 4220 if (HasProfileData) 4221 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness)); 4222 } 4223 4224 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev); 4225 unsigned Code = 4226 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED); 4227 4228 // Emit the finished record. 4229 Stream.EmitRecord(Code, NameVals, FSAbbrev); 4230 NameVals.clear(); 4231 MaybeEmitOriginalName(*S); 4232 }); 4233 4234 for (auto *AS : Aliases) { 4235 auto AliasValueId = SummaryToValueIdMap[AS]; 4236 assert(AliasValueId); 4237 NameVals.push_back(AliasValueId); 4238 NameVals.push_back(Index.getModuleId(AS->modulePath())); 4239 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags())); 4240 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()]; 4241 assert(AliaseeValueId); 4242 NameVals.push_back(AliaseeValueId); 4243 4244 // Emit the finished record. 4245 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev); 4246 NameVals.clear(); 4247 MaybeEmitOriginalName(*AS); 4248 4249 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee())) 4250 getReferencedTypeIds(FS, ReferencedTypeIds); 4251 } 4252 4253 if (!Index.cfiFunctionDefs().empty()) { 4254 for (auto &S : Index.cfiFunctionDefs()) { 4255 if (DefOrUseGUIDs.count( 4256 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) { 4257 NameVals.push_back(StrtabBuilder.add(S)); 4258 NameVals.push_back(S.size()); 4259 } 4260 } 4261 if (!NameVals.empty()) { 4262 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals); 4263 NameVals.clear(); 4264 } 4265 } 4266 4267 if (!Index.cfiFunctionDecls().empty()) { 4268 for (auto &S : Index.cfiFunctionDecls()) { 4269 if (DefOrUseGUIDs.count( 4270 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) { 4271 NameVals.push_back(StrtabBuilder.add(S)); 4272 NameVals.push_back(S.size()); 4273 } 4274 } 4275 if (!NameVals.empty()) { 4276 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals); 4277 NameVals.clear(); 4278 } 4279 } 4280 4281 // Walk the GUIDs that were referenced, and write the 4282 // corresponding type id records. 4283 for (auto &T : ReferencedTypeIds) { 4284 auto TidIter = Index.typeIds().equal_range(T); 4285 for (auto It = TidIter.first; It != TidIter.second; ++It) { 4286 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first, 4287 It->second.second); 4288 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals); 4289 NameVals.clear(); 4290 } 4291 } 4292 4293 Stream.EmitRecord(bitc::FS_BLOCK_COUNT, 4294 ArrayRef<uint64_t>{Index.getBlockCount()}); 4295 4296 Stream.ExitBlock(); 4297 } 4298 4299 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the 4300 /// current llvm version, and a record for the epoch number. 4301 static void writeIdentificationBlock(BitstreamWriter &Stream) { 4302 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5); 4303 4304 // Write the "user readable" string identifying the bitcode producer 4305 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4306 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING)); 4307 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4308 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 4309 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4310 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING, 4311 "LLVM" LLVM_VERSION_STRING, StringAbbrev); 4312 4313 // Write the epoch version 4314 Abbv = std::make_shared<BitCodeAbbrev>(); 4315 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH)); 4316 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 4317 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4318 constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}}; 4319 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev); 4320 Stream.ExitBlock(); 4321 } 4322 4323 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) { 4324 // Emit the module's hash. 4325 // MODULE_CODE_HASH: [5*i32] 4326 if (GenerateHash) { 4327 uint32_t Vals[5]; 4328 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos], 4329 Buffer.size() - BlockStartPos)); 4330 StringRef Hash = Hasher.result(); 4331 for (int Pos = 0; Pos < 20; Pos += 4) { 4332 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos); 4333 } 4334 4335 // Emit the finished record. 4336 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals); 4337 4338 if (ModHash) 4339 // Save the written hash value. 4340 llvm::copy(Vals, std::begin(*ModHash)); 4341 } 4342 } 4343 4344 void ModuleBitcodeWriter::write() { 4345 writeIdentificationBlock(Stream); 4346 4347 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 4348 size_t BlockStartPos = Buffer.size(); 4349 4350 writeModuleVersion(); 4351 4352 // Emit blockinfo, which defines the standard abbreviations etc. 4353 writeBlockInfo(); 4354 4355 // Emit information describing all of the types in the module. 4356 writeTypeTable(); 4357 4358 // Emit information about attribute groups. 4359 writeAttributeGroupTable(); 4360 4361 // Emit information about parameter attributes. 4362 writeAttributeTable(); 4363 4364 writeComdats(); 4365 4366 // Emit top-level description of module, including target triple, inline asm, 4367 // descriptors for global variables, and function prototype info. 4368 writeModuleInfo(); 4369 4370 // Emit constants. 4371 writeModuleConstants(); 4372 4373 // Emit metadata kind names. 4374 writeModuleMetadataKinds(); 4375 4376 // Emit metadata. 4377 writeModuleMetadata(); 4378 4379 // Emit module-level use-lists. 4380 if (VE.shouldPreserveUseListOrder()) 4381 writeUseListBlock(nullptr); 4382 4383 writeOperandBundleTags(); 4384 writeSyncScopeNames(); 4385 4386 // Emit function bodies. 4387 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex; 4388 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F) 4389 if (!F->isDeclaration()) 4390 writeFunction(*F, FunctionToBitcodeIndex); 4391 4392 // Need to write after the above call to WriteFunction which populates 4393 // the summary information in the index. 4394 if (Index) 4395 writePerModuleGlobalValueSummary(); 4396 4397 writeGlobalValueSymbolTable(FunctionToBitcodeIndex); 4398 4399 writeModuleHash(BlockStartPos); 4400 4401 Stream.ExitBlock(); 4402 } 4403 4404 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer, 4405 uint32_t &Position) { 4406 support::endian::write32le(&Buffer[Position], Value); 4407 Position += 4; 4408 } 4409 4410 /// If generating a bc file on darwin, we have to emit a 4411 /// header and trailer to make it compatible with the system archiver. To do 4412 /// this we emit the following header, and then emit a trailer that pads the 4413 /// file out to be a multiple of 16 bytes. 4414 /// 4415 /// struct bc_header { 4416 /// uint32_t Magic; // 0x0B17C0DE 4417 /// uint32_t Version; // Version, currently always 0. 4418 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file. 4419 /// uint32_t BitcodeSize; // Size of traditional bitcode file. 4420 /// uint32_t CPUType; // CPU specifier. 4421 /// ... potentially more later ... 4422 /// }; 4423 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer, 4424 const Triple &TT) { 4425 unsigned CPUType = ~0U; 4426 4427 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*, 4428 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic 4429 // number from /usr/include/mach/machine.h. It is ok to reproduce the 4430 // specific constants here because they are implicitly part of the Darwin ABI. 4431 enum { 4432 DARWIN_CPU_ARCH_ABI64 = 0x01000000, 4433 DARWIN_CPU_TYPE_X86 = 7, 4434 DARWIN_CPU_TYPE_ARM = 12, 4435 DARWIN_CPU_TYPE_POWERPC = 18 4436 }; 4437 4438 Triple::ArchType Arch = TT.getArch(); 4439 if (Arch == Triple::x86_64) 4440 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64; 4441 else if (Arch == Triple::x86) 4442 CPUType = DARWIN_CPU_TYPE_X86; 4443 else if (Arch == Triple::ppc) 4444 CPUType = DARWIN_CPU_TYPE_POWERPC; 4445 else if (Arch == Triple::ppc64) 4446 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64; 4447 else if (Arch == Triple::arm || Arch == Triple::thumb) 4448 CPUType = DARWIN_CPU_TYPE_ARM; 4449 4450 // Traditional Bitcode starts after header. 4451 assert(Buffer.size() >= BWH_HeaderSize && 4452 "Expected header size to be reserved"); 4453 unsigned BCOffset = BWH_HeaderSize; 4454 unsigned BCSize = Buffer.size() - BWH_HeaderSize; 4455 4456 // Write the magic and version. 4457 unsigned Position = 0; 4458 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position); 4459 writeInt32ToBuffer(0, Buffer, Position); // Version. 4460 writeInt32ToBuffer(BCOffset, Buffer, Position); 4461 writeInt32ToBuffer(BCSize, Buffer, Position); 4462 writeInt32ToBuffer(CPUType, Buffer, Position); 4463 4464 // If the file is not a multiple of 16 bytes, insert dummy padding. 4465 while (Buffer.size() & 15) 4466 Buffer.push_back(0); 4467 } 4468 4469 /// Helper to write the header common to all bitcode files. 4470 static void writeBitcodeHeader(BitstreamWriter &Stream) { 4471 // Emit the file header. 4472 Stream.Emit((unsigned)'B', 8); 4473 Stream.Emit((unsigned)'C', 8); 4474 Stream.Emit(0x0, 4); 4475 Stream.Emit(0xC, 4); 4476 Stream.Emit(0xE, 4); 4477 Stream.Emit(0xD, 4); 4478 } 4479 4480 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer, raw_fd_stream *FS) 4481 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer, FS, FlushThreshold)) { 4482 writeBitcodeHeader(*Stream); 4483 } 4484 4485 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); } 4486 4487 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) { 4488 Stream->EnterSubblock(Block, 3); 4489 4490 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4491 Abbv->Add(BitCodeAbbrevOp(Record)); 4492 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 4493 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv)); 4494 4495 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob); 4496 4497 Stream->ExitBlock(); 4498 } 4499 4500 void BitcodeWriter::writeSymtab() { 4501 assert(!WroteStrtab && !WroteSymtab); 4502 4503 // If any module has module-level inline asm, we will require a registered asm 4504 // parser for the target so that we can create an accurate symbol table for 4505 // the module. 4506 for (Module *M : Mods) { 4507 if (M->getModuleInlineAsm().empty()) 4508 continue; 4509 4510 std::string Err; 4511 const Triple TT(M->getTargetTriple()); 4512 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err); 4513 if (!T || !T->hasMCAsmParser()) 4514 return; 4515 } 4516 4517 WroteSymtab = true; 4518 SmallVector<char, 0> Symtab; 4519 // The irsymtab::build function may be unable to create a symbol table if the 4520 // module is malformed (e.g. it contains an invalid alias). Writing a symbol 4521 // table is not required for correctness, but we still want to be able to 4522 // write malformed modules to bitcode files, so swallow the error. 4523 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) { 4524 consumeError(std::move(E)); 4525 return; 4526 } 4527 4528 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB, 4529 {Symtab.data(), Symtab.size()}); 4530 } 4531 4532 void BitcodeWriter::writeStrtab() { 4533 assert(!WroteStrtab); 4534 4535 std::vector<char> Strtab; 4536 StrtabBuilder.finalizeInOrder(); 4537 Strtab.resize(StrtabBuilder.getSize()); 4538 StrtabBuilder.write((uint8_t *)Strtab.data()); 4539 4540 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, 4541 {Strtab.data(), Strtab.size()}); 4542 4543 WroteStrtab = true; 4544 } 4545 4546 void BitcodeWriter::copyStrtab(StringRef Strtab) { 4547 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab); 4548 WroteStrtab = true; 4549 } 4550 4551 void BitcodeWriter::writeModule(const Module &M, 4552 bool ShouldPreserveUseListOrder, 4553 const ModuleSummaryIndex *Index, 4554 bool GenerateHash, ModuleHash *ModHash) { 4555 assert(!WroteStrtab); 4556 4557 // The Mods vector is used by irsymtab::build, which requires non-const 4558 // Modules in case it needs to materialize metadata. But the bitcode writer 4559 // requires that the module is materialized, so we can cast to non-const here, 4560 // after checking that it is in fact materialized. 4561 assert(M.isMaterialized()); 4562 Mods.push_back(const_cast<Module *>(&M)); 4563 4564 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream, 4565 ShouldPreserveUseListOrder, Index, 4566 GenerateHash, ModHash); 4567 ModuleWriter.write(); 4568 } 4569 4570 void BitcodeWriter::writeIndex( 4571 const ModuleSummaryIndex *Index, 4572 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) { 4573 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, 4574 ModuleToSummariesForIndex); 4575 IndexWriter.write(); 4576 } 4577 4578 /// Write the specified module to the specified output stream. 4579 void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out, 4580 bool ShouldPreserveUseListOrder, 4581 const ModuleSummaryIndex *Index, 4582 bool GenerateHash, ModuleHash *ModHash) { 4583 SmallVector<char, 0> Buffer; 4584 Buffer.reserve(256*1024); 4585 4586 // If this is darwin or another generic macho target, reserve space for the 4587 // header. 4588 Triple TT(M.getTargetTriple()); 4589 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 4590 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0); 4591 4592 BitcodeWriter Writer(Buffer, dyn_cast<raw_fd_stream>(&Out)); 4593 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash, 4594 ModHash); 4595 Writer.writeSymtab(); 4596 Writer.writeStrtab(); 4597 4598 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 4599 emitDarwinBCHeaderAndTrailer(Buffer, TT); 4600 4601 // Write the generated bitstream to "Out". 4602 if (!Buffer.empty()) 4603 Out.write((char *)&Buffer.front(), Buffer.size()); 4604 } 4605 4606 void IndexBitcodeWriter::write() { 4607 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 4608 4609 writeModuleVersion(); 4610 4611 // Write the module paths in the combined index. 4612 writeModStrings(); 4613 4614 // Write the summary combined index records. 4615 writeCombinedGlobalValueSummary(); 4616 4617 Stream.ExitBlock(); 4618 } 4619 4620 // Write the specified module summary index to the given raw output stream, 4621 // where it will be written in a new bitcode block. This is used when 4622 // writing the combined index file for ThinLTO. When writing a subset of the 4623 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map. 4624 void llvm::WriteIndexToFile( 4625 const ModuleSummaryIndex &Index, raw_ostream &Out, 4626 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) { 4627 SmallVector<char, 0> Buffer; 4628 Buffer.reserve(256 * 1024); 4629 4630 BitcodeWriter Writer(Buffer); 4631 Writer.writeIndex(&Index, ModuleToSummariesForIndex); 4632 Writer.writeStrtab(); 4633 4634 Out.write((char *)&Buffer.front(), Buffer.size()); 4635 } 4636 4637 namespace { 4638 4639 /// Class to manage the bitcode writing for a thin link bitcode file. 4640 class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase { 4641 /// ModHash is for use in ThinLTO incremental build, generated while writing 4642 /// the module bitcode file. 4643 const ModuleHash *ModHash; 4644 4645 public: 4646 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder, 4647 BitstreamWriter &Stream, 4648 const ModuleSummaryIndex &Index, 4649 const ModuleHash &ModHash) 4650 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream, 4651 /*ShouldPreserveUseListOrder=*/false, &Index), 4652 ModHash(&ModHash) {} 4653 4654 void write(); 4655 4656 private: 4657 void writeSimplifiedModuleInfo(); 4658 }; 4659 4660 } // end anonymous namespace 4661 4662 // This function writes a simpilified module info for thin link bitcode file. 4663 // It only contains the source file name along with the name(the offset and 4664 // size in strtab) and linkage for global values. For the global value info 4665 // entry, in order to keep linkage at offset 5, there are three zeros used 4666 // as padding. 4667 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() { 4668 SmallVector<unsigned, 64> Vals; 4669 // Emit the module's source file name. 4670 { 4671 StringEncoding Bits = getStringEncoding(M.getSourceFileName()); 4672 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8); 4673 if (Bits == SE_Char6) 4674 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6); 4675 else if (Bits == SE_Fixed7) 4676 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7); 4677 4678 // MODULE_CODE_SOURCE_FILENAME: [namechar x N] 4679 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4680 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME)); 4681 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4682 Abbv->Add(AbbrevOpToUse); 4683 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4684 4685 for (const auto P : M.getSourceFileName()) 4686 Vals.push_back((unsigned char)P); 4687 4688 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev); 4689 Vals.clear(); 4690 } 4691 4692 // Emit the global variable information. 4693 for (const GlobalVariable &GV : M.globals()) { 4694 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage] 4695 Vals.push_back(StrtabBuilder.add(GV.getName())); 4696 Vals.push_back(GV.getName().size()); 4697 Vals.push_back(0); 4698 Vals.push_back(0); 4699 Vals.push_back(0); 4700 Vals.push_back(getEncodedLinkage(GV)); 4701 4702 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals); 4703 Vals.clear(); 4704 } 4705 4706 // Emit the function proto information. 4707 for (const Function &F : M) { 4708 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage] 4709 Vals.push_back(StrtabBuilder.add(F.getName())); 4710 Vals.push_back(F.getName().size()); 4711 Vals.push_back(0); 4712 Vals.push_back(0); 4713 Vals.push_back(0); 4714 Vals.push_back(getEncodedLinkage(F)); 4715 4716 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals); 4717 Vals.clear(); 4718 } 4719 4720 // Emit the alias information. 4721 for (const GlobalAlias &A : M.aliases()) { 4722 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage] 4723 Vals.push_back(StrtabBuilder.add(A.getName())); 4724 Vals.push_back(A.getName().size()); 4725 Vals.push_back(0); 4726 Vals.push_back(0); 4727 Vals.push_back(0); 4728 Vals.push_back(getEncodedLinkage(A)); 4729 4730 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals); 4731 Vals.clear(); 4732 } 4733 4734 // Emit the ifunc information. 4735 for (const GlobalIFunc &I : M.ifuncs()) { 4736 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage] 4737 Vals.push_back(StrtabBuilder.add(I.getName())); 4738 Vals.push_back(I.getName().size()); 4739 Vals.push_back(0); 4740 Vals.push_back(0); 4741 Vals.push_back(0); 4742 Vals.push_back(getEncodedLinkage(I)); 4743 4744 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals); 4745 Vals.clear(); 4746 } 4747 } 4748 4749 void ThinLinkBitcodeWriter::write() { 4750 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 4751 4752 writeModuleVersion(); 4753 4754 writeSimplifiedModuleInfo(); 4755 4756 writePerModuleGlobalValueSummary(); 4757 4758 // Write module hash. 4759 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash)); 4760 4761 Stream.ExitBlock(); 4762 } 4763 4764 void BitcodeWriter::writeThinLinkBitcode(const Module &M, 4765 const ModuleSummaryIndex &Index, 4766 const ModuleHash &ModHash) { 4767 assert(!WroteStrtab); 4768 4769 // The Mods vector is used by irsymtab::build, which requires non-const 4770 // Modules in case it needs to materialize metadata. But the bitcode writer 4771 // requires that the module is materialized, so we can cast to non-const here, 4772 // after checking that it is in fact materialized. 4773 assert(M.isMaterialized()); 4774 Mods.push_back(const_cast<Module *>(&M)); 4775 4776 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index, 4777 ModHash); 4778 ThinLinkWriter.write(); 4779 } 4780 4781 // Write the specified thin link bitcode file to the given raw output stream, 4782 // where it will be written in a new bitcode block. This is used when 4783 // writing the per-module index file for ThinLTO. 4784 void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, 4785 const ModuleSummaryIndex &Index, 4786 const ModuleHash &ModHash) { 4787 SmallVector<char, 0> Buffer; 4788 Buffer.reserve(256 * 1024); 4789 4790 BitcodeWriter Writer(Buffer); 4791 Writer.writeThinLinkBitcode(M, Index, ModHash); 4792 Writer.writeSymtab(); 4793 Writer.writeStrtab(); 4794 4795 Out.write((char *)&Buffer.front(), Buffer.size()); 4796 } 4797 4798 static const char *getSectionNameForBitcode(const Triple &T) { 4799 switch (T.getObjectFormat()) { 4800 case Triple::MachO: 4801 return "__LLVM,__bitcode"; 4802 case Triple::COFF: 4803 case Triple::ELF: 4804 case Triple::Wasm: 4805 case Triple::UnknownObjectFormat: 4806 return ".llvmbc"; 4807 case Triple::GOFF: 4808 llvm_unreachable("GOFF is not yet implemented"); 4809 break; 4810 case Triple::XCOFF: 4811 llvm_unreachable("XCOFF is not yet implemented"); 4812 break; 4813 } 4814 llvm_unreachable("Unimplemented ObjectFormatType"); 4815 } 4816 4817 static const char *getSectionNameForCommandline(const Triple &T) { 4818 switch (T.getObjectFormat()) { 4819 case Triple::MachO: 4820 return "__LLVM,__cmdline"; 4821 case Triple::COFF: 4822 case Triple::ELF: 4823 case Triple::Wasm: 4824 case Triple::UnknownObjectFormat: 4825 return ".llvmcmd"; 4826 case Triple::GOFF: 4827 llvm_unreachable("GOFF is not yet implemented"); 4828 break; 4829 case Triple::XCOFF: 4830 llvm_unreachable("XCOFF is not yet implemented"); 4831 break; 4832 } 4833 llvm_unreachable("Unimplemented ObjectFormatType"); 4834 } 4835 4836 void llvm::EmbedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf, 4837 bool EmbedBitcode, bool EmbedCmdline, 4838 const std::vector<uint8_t> &CmdArgs) { 4839 // Save llvm.compiler.used and remove it. 4840 SmallVector<Constant *, 2> UsedArray; 4841 SmallPtrSet<GlobalValue *, 4> UsedGlobals; 4842 Type *UsedElementType = Type::getInt8Ty(M.getContext())->getPointerTo(0); 4843 GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true); 4844 for (auto *GV : UsedGlobals) { 4845 if (GV->getName() != "llvm.embedded.module" && 4846 GV->getName() != "llvm.cmdline") 4847 UsedArray.push_back( 4848 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 4849 } 4850 if (Used) 4851 Used->eraseFromParent(); 4852 4853 // Embed the bitcode for the llvm module. 4854 std::string Data; 4855 ArrayRef<uint8_t> ModuleData; 4856 Triple T(M.getTargetTriple()); 4857 4858 if (EmbedBitcode) { 4859 if (Buf.getBufferSize() == 0 || 4860 !isBitcode((const unsigned char *)Buf.getBufferStart(), 4861 (const unsigned char *)Buf.getBufferEnd())) { 4862 // If the input is LLVM Assembly, bitcode is produced by serializing 4863 // the module. Use-lists order need to be preserved in this case. 4864 llvm::raw_string_ostream OS(Data); 4865 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true); 4866 ModuleData = 4867 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size()); 4868 } else 4869 // If the input is LLVM bitcode, write the input byte stream directly. 4870 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(), 4871 Buf.getBufferSize()); 4872 } 4873 llvm::Constant *ModuleConstant = 4874 llvm::ConstantDataArray::get(M.getContext(), ModuleData); 4875 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 4876 M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage, 4877 ModuleConstant); 4878 GV->setSection(getSectionNameForBitcode(T)); 4879 // Set alignment to 1 to prevent padding between two contributions from input 4880 // sections after linking. 4881 GV->setAlignment(Align(1)); 4882 UsedArray.push_back( 4883 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 4884 if (llvm::GlobalVariable *Old = 4885 M.getGlobalVariable("llvm.embedded.module", true)) { 4886 assert(Old->hasOneUse() && 4887 "llvm.embedded.module can only be used once in llvm.compiler.used"); 4888 GV->takeName(Old); 4889 Old->eraseFromParent(); 4890 } else { 4891 GV->setName("llvm.embedded.module"); 4892 } 4893 4894 // Skip if only bitcode needs to be embedded. 4895 if (EmbedCmdline) { 4896 // Embed command-line options. 4897 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()), 4898 CmdArgs.size()); 4899 llvm::Constant *CmdConstant = 4900 llvm::ConstantDataArray::get(M.getContext(), CmdData); 4901 GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true, 4902 llvm::GlobalValue::PrivateLinkage, 4903 CmdConstant); 4904 GV->setSection(getSectionNameForCommandline(T)); 4905 GV->setAlignment(Align(1)); 4906 UsedArray.push_back( 4907 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 4908 if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) { 4909 assert(Old->hasOneUse() && 4910 "llvm.cmdline can only be used once in llvm.compiler.used"); 4911 GV->takeName(Old); 4912 Old->eraseFromParent(); 4913 } else { 4914 GV->setName("llvm.cmdline"); 4915 } 4916 } 4917 4918 if (UsedArray.empty()) 4919 return; 4920 4921 // Recreate llvm.compiler.used. 4922 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size()); 4923 auto *NewUsed = new GlobalVariable( 4924 M, ATy, false, llvm::GlobalValue::AppendingLinkage, 4925 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used"); 4926 NewUsed->setSection("llvm.metadata"); 4927 } 4928