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