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