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