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