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