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