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