LLVM 18.0.0git
BitcodeWriter.cpp
Go to the documentation of this file.
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
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/STLExtras.h"
20#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/StringMap.h"
25#include "llvm/ADT/StringRef.h"
31#include "llvm/Config/llvm-config.h"
32#include "llvm/IR/Attributes.h"
33#include "llvm/IR/BasicBlock.h"
34#include "llvm/IR/Comdat.h"
35#include "llvm/IR/Constant.h"
36#include "llvm/IR/Constants.h"
38#include "llvm/IR/DebugLoc.h"
40#include "llvm/IR/Function.h"
41#include "llvm/IR/GlobalAlias.h"
42#include "llvm/IR/GlobalIFunc.h"
44#include "llvm/IR/GlobalValue.h"
46#include "llvm/IR/InlineAsm.h"
47#include "llvm/IR/InstrTypes.h"
48#include "llvm/IR/Instruction.h"
50#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/Metadata.h"
52#include "llvm/IR/Module.h"
54#include "llvm/IR/Operator.h"
55#include "llvm/IR/Type.h"
57#include "llvm/IR/Value.h"
65#include "llvm/Support/Endian.h"
66#include "llvm/Support/Error.h"
69#include "llvm/Support/SHA1.h"
72#include <algorithm>
73#include <cassert>
74#include <cstddef>
75#include <cstdint>
76#include <iterator>
77#include <map>
78#include <memory>
79#include <optional>
80#include <string>
81#include <utility>
82#include <vector>
83
84using namespace llvm;
85
87 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
88 cl::desc("Number of metadatas above which we emit an index "
89 "to enable lazy-loading"));
91 "bitcode-flush-threshold", cl::Hidden, cl::init(512),
92 cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
93
95 "write-relbf-to-summary", cl::Hidden, cl::init(false),
96 cl::desc("Write relative block frequency to function summary "));
97
98namespace llvm {
100}
101
102namespace {
103
104/// These are manifest constants used by the bitcode writer. They do not need to
105/// be kept in sync with the reader, but need to be consistent within this file.
106enum {
107 // VALUE_SYMTAB_BLOCK abbrev id's.
108 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
109 VST_ENTRY_7_ABBREV,
110 VST_ENTRY_6_ABBREV,
111 VST_BBENTRY_6_ABBREV,
112
113 // CONSTANTS_BLOCK abbrev id's.
114 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
115 CONSTANTS_INTEGER_ABBREV,
116 CONSTANTS_CE_CAST_Abbrev,
117 CONSTANTS_NULL_Abbrev,
118
119 // FUNCTION_BLOCK abbrev id's.
120 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
121 FUNCTION_INST_UNOP_ABBREV,
122 FUNCTION_INST_UNOP_FLAGS_ABBREV,
123 FUNCTION_INST_BINOP_ABBREV,
124 FUNCTION_INST_BINOP_FLAGS_ABBREV,
125 FUNCTION_INST_CAST_ABBREV,
126 FUNCTION_INST_RET_VOID_ABBREV,
127 FUNCTION_INST_RET_VAL_ABBREV,
128 FUNCTION_INST_UNREACHABLE_ABBREV,
129 FUNCTION_INST_GEP_ABBREV,
130};
131
132/// Abstract class to manage the bitcode writing, subclassed for each bitcode
133/// file type.
134class BitcodeWriterBase {
135protected:
136 /// The stream created and owned by the client.
137 BitstreamWriter &Stream;
138
139 StringTableBuilder &StrtabBuilder;
140
141public:
142 /// Constructs a BitcodeWriterBase object that writes to the provided
143 /// \p Stream.
144 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
145 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
146
147protected:
148 void writeModuleVersion();
149};
150
151void BitcodeWriterBase::writeModuleVersion() {
152 // VERSION: [version#]
153 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
154}
155
156/// Base class to manage the module bitcode writing, currently subclassed for
157/// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
158class ModuleBitcodeWriterBase : public BitcodeWriterBase {
159protected:
160 /// The Module to write to bitcode.
161 const Module &M;
162
163 /// Enumerates ids for all values in the module.
165
166 /// Optional per-module index to write for ThinLTO.
168
169 /// Map that holds the correspondence between GUIDs in the summary index,
170 /// that came from indirect call profiles, and a value id generated by this
171 /// class to use in the VST and summary block records.
172 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
173
174 /// Tracks the last value id recorded in the GUIDToValueMap.
175 unsigned GlobalValueId;
176
177 /// Saves the offset of the VSTOffset record that must eventually be
178 /// backpatched with the offset of the actual VST.
179 uint64_t VSTOffsetPlaceholder = 0;
180
181public:
182 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
183 /// writing to the provided \p Buffer.
184 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
185 BitstreamWriter &Stream,
186 bool ShouldPreserveUseListOrder,
188 : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
189 VE(M, ShouldPreserveUseListOrder), Index(Index) {
190 // Assign ValueIds to any callee values in the index that came from
191 // indirect call profiles and were recorded as a GUID not a Value*
192 // (which would have been assigned an ID by the ValueEnumerator).
193 // The starting ValueId is just after the number of values in the
194 // ValueEnumerator, so that they can be emitted in the VST.
195 GlobalValueId = VE.getValues().size();
196 if (!Index)
197 return;
198 for (const auto &GUIDSummaryLists : *Index)
199 // Examine all summaries for this GUID.
200 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
201 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
202 // For each call in the function summary, see if the call
203 // is to a GUID (which means it is for an indirect call,
204 // otherwise we would have a Value for it). If so, synthesize
205 // a value id.
206 for (auto &CallEdge : FS->calls())
207 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
208 assignValueId(CallEdge.first.getGUID());
209 }
210
211protected:
212 void writePerModuleGlobalValueSummary();
213
214private:
215 void writePerModuleFunctionSummaryRecord(
217 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
218 unsigned CallsiteAbbrev, unsigned AllocAbbrev, const Function &F);
219 void writeModuleLevelReferences(const GlobalVariable &V,
221 unsigned FSModRefsAbbrev,
222 unsigned FSModVTableRefsAbbrev);
223
224 void assignValueId(GlobalValue::GUID ValGUID) {
225 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
226 }
227
228 unsigned getValueId(GlobalValue::GUID ValGUID) {
229 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
230 // Expect that any GUID value had a value Id assigned by an
231 // earlier call to assignValueId.
232 assert(VMI != GUIDToValueIdMap.end() &&
233 "GUID does not have assigned value Id");
234 return VMI->second;
235 }
236
237 // Helper to get the valueId for the type of value recorded in VI.
238 unsigned getValueId(ValueInfo VI) {
239 if (!VI.haveGVs() || !VI.getValue())
240 return getValueId(VI.getGUID());
241 return VE.getValueID(VI.getValue());
242 }
243
244 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
245};
246
247/// Class to manage the bitcode writing for a module.
248class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
249 /// Pointer to the buffer allocated by caller for bitcode writing.
250 const SmallVectorImpl<char> &Buffer;
251
252 /// True if a module hash record should be written.
253 bool GenerateHash;
254
255 /// If non-null, when GenerateHash is true, the resulting hash is written
256 /// into ModHash.
257 ModuleHash *ModHash;
258
259 SHA1 Hasher;
260
261 /// The start bit of the identification block.
262 uint64_t BitcodeStartBit;
263
264public:
265 /// Constructs a ModuleBitcodeWriter object for the given Module,
266 /// writing to the provided \p Buffer.
267 ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
268 StringTableBuilder &StrtabBuilder,
269 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
270 const ModuleSummaryIndex *Index, bool GenerateHash,
271 ModuleHash *ModHash = nullptr)
272 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
273 ShouldPreserveUseListOrder, Index),
274 Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
275 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
276
277 /// Emit the current module to the bitstream.
278 void write();
279
280private:
281 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
282
283 size_t addToStrtab(StringRef Str);
284
285 void writeAttributeGroupTable();
286 void writeAttributeTable();
287 void writeTypeTable();
288 void writeComdats();
289 void writeValueSymbolTableForwardDecl();
290 void writeModuleInfo();
291 void writeValueAsMetadata(const ValueAsMetadata *MD,
294 unsigned Abbrev);
295 unsigned createDILocationAbbrev();
297 unsigned &Abbrev);
298 unsigned createGenericDINodeAbbrev();
300 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
302 unsigned Abbrev);
305 unsigned Abbrev);
306 void writeDIEnumerator(const DIEnumerator *N,
307 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
309 unsigned Abbrev);
310 void writeDIStringType(const DIStringType *N,
311 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
313 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
315 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
318 unsigned Abbrev);
320 unsigned Abbrev);
322 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
323 void writeDISubprogram(const DISubprogram *N,
324 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
326 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
329 unsigned Abbrev);
331 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
333 unsigned Abbrev);
335 unsigned Abbrev);
337 unsigned Abbrev);
339 unsigned Abbrev);
341 unsigned Abbrev);
343 unsigned Abbrev);
346 unsigned Abbrev);
349 unsigned Abbrev);
352 unsigned Abbrev);
354 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
355 void writeDILabel(const DILabel *N,
356 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
357 void writeDIExpression(const DIExpression *N,
358 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
361 unsigned Abbrev);
363 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
366 unsigned Abbrev);
367 unsigned createNamedMetadataAbbrev();
368 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
369 unsigned createMetadataStringsAbbrev();
370 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
372 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
374 std::vector<unsigned> *MDAbbrevs = nullptr,
375 std::vector<uint64_t> *IndexPos = nullptr);
376 void writeModuleMetadata();
377 void writeFunctionMetadata(const Function &F);
378 void writeFunctionMetadataAttachment(const Function &F);
379 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
380 const GlobalObject &GO);
381 void writeModuleMetadataKinds();
382 void writeOperandBundleTags();
383 void writeSyncScopeNames();
384 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
385 void writeModuleConstants();
386 bool pushValueAndType(const Value *V, unsigned InstID,
388 void writeOperandBundles(const CallBase &CB, unsigned InstID);
389 void pushValue(const Value *V, unsigned InstID,
391 void pushValueSigned(const Value *V, unsigned InstID,
393 void writeInstruction(const Instruction &I, unsigned InstID,
395 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
396 void writeGlobalValueSymbolTable(
397 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
398 void writeUseList(UseListOrder &&Order);
399 void writeUseListBlock(const Function *F);
400 void
401 writeFunction(const Function &F,
402 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
403 void writeBlockInfo();
404 void writeModuleHash(size_t BlockStartPos);
405
406 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
407 return unsigned(SSID);
408 }
409
410 unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
411};
412
413/// Class to manage the bitcode writing for a combined index.
414class IndexBitcodeWriter : public BitcodeWriterBase {
415 /// The combined index to write to bitcode.
417
418 /// When writing a subset of the index for distributed backends, client
419 /// provides a map of modules to the corresponding GUIDs/summaries to write.
420 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
421
422 /// Map that holds the correspondence between the GUID used in the combined
423 /// index and a value id generated by this class to use in references.
424 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
425
426 // The sorted stack id indices actually used in the summary entries being
427 // written, which will be a subset of those in the full index in the case of
428 // distributed indexes.
429 std::vector<unsigned> StackIdIndices;
430
431 /// Tracks the last value id recorded in the GUIDToValueMap.
432 unsigned GlobalValueId = 0;
433
434 /// Tracks the assignment of module paths in the module path string table to
435 /// an id assigned for use in summary references to the module path.
437
438public:
439 /// Constructs a IndexBitcodeWriter object for the given combined index,
440 /// writing to the provided \p Buffer. When writing a subset of the index
441 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
442 IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
444 const std::map<std::string, GVSummaryMapTy>
445 *ModuleToSummariesForIndex = nullptr)
446 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
447 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
448 // Assign unique value ids to all summaries to be written, for use
449 // in writing out the call graph edges. Save the mapping from GUID
450 // to the new global value id to use when writing those edges, which
451 // are currently saved in the index in terms of GUID.
452 forEachSummary([&](GVInfo I, bool IsAliasee) {
453 GUIDToValueIdMap[I.first] = ++GlobalValueId;
454 if (IsAliasee)
455 return;
456 auto *FS = dyn_cast<FunctionSummary>(I.second);
457 if (!FS)
458 return;
459 // Record all stack id indices actually used in the summary entries being
460 // written, so that we can compact them in the case of distributed ThinLTO
461 // indexes.
462 for (auto &CI : FS->callsites())
463 for (auto Idx : CI.StackIdIndices)
464 StackIdIndices.push_back(Idx);
465 for (auto &AI : FS->allocs())
466 for (auto &MIB : AI.MIBs)
467 for (auto Idx : MIB.StackIdIndices)
468 StackIdIndices.push_back(Idx);
469 });
470 llvm::sort(StackIdIndices);
471 StackIdIndices.erase(
472 std::unique(StackIdIndices.begin(), StackIdIndices.end()),
473 StackIdIndices.end());
474 }
475
476 /// The below iterator returns the GUID and associated summary.
477 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
478
479 /// Calls the callback for each value GUID and summary to be written to
480 /// bitcode. This hides the details of whether they are being pulled from the
481 /// entire index or just those in a provided ModuleToSummariesForIndex map.
482 template<typename Functor>
483 void forEachSummary(Functor Callback) {
484 if (ModuleToSummariesForIndex) {
485 for (auto &M : *ModuleToSummariesForIndex)
486 for (auto &Summary : M.second) {
487 Callback(Summary, false);
488 // Ensure aliasee is handled, e.g. for assigning a valueId,
489 // even if we are not importing the aliasee directly (the
490 // imported alias will contain a copy of aliasee).
491 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
492 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
493 }
494 } else {
495 for (auto &Summaries : Index)
496 for (auto &Summary : Summaries.second.SummaryList)
497 Callback({Summaries.first, Summary.get()}, false);
498 }
499 }
500
501 /// Calls the callback for each entry in the modulePaths StringMap that
502 /// should be written to the module path string table. This hides the details
503 /// of whether they are being pulled from the entire index or just those in a
504 /// provided ModuleToSummariesForIndex map.
505 template <typename Functor> void forEachModule(Functor Callback) {
506 if (ModuleToSummariesForIndex) {
507 for (const auto &M : *ModuleToSummariesForIndex) {
508 const auto &MPI = Index.modulePaths().find(M.first);
509 if (MPI == Index.modulePaths().end()) {
510 // This should only happen if the bitcode file was empty, in which
511 // case we shouldn't be importing (the ModuleToSummariesForIndex
512 // would only include the module we are writing and index for).
513 assert(ModuleToSummariesForIndex->size() == 1);
514 continue;
515 }
516 Callback(*MPI);
517 }
518 } else {
519 // Since StringMap iteration order isn't guaranteed, order by path string
520 // first.
521 // FIXME: Make this a vector of StringMapEntry instead to avoid the later
522 // map lookup.
523 std::vector<StringRef> ModulePaths;
524 for (auto &[ModPath, _] : Index.modulePaths())
525 ModulePaths.push_back(ModPath);
526 llvm::sort(ModulePaths.begin(), ModulePaths.end());
527 for (auto &ModPath : ModulePaths)
528 Callback(*Index.modulePaths().find(ModPath));
529 }
530 }
531
532 /// Main entry point for writing a combined index to bitcode.
533 void write();
534
535private:
536 void writeModStrings();
537 void writeCombinedGlobalValueSummary();
538
539 std::optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
540 auto VMI = GUIDToValueIdMap.find(ValGUID);
541 if (VMI == GUIDToValueIdMap.end())
542 return std::nullopt;
543 return VMI->second;
544 }
545
546 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
547};
548
549} // end anonymous namespace
550
551static unsigned getEncodedCastOpcode(unsigned Opcode) {
552 switch (Opcode) {
553 default: llvm_unreachable("Unknown cast instruction!");
554 case Instruction::Trunc : return bitc::CAST_TRUNC;
555 case Instruction::ZExt : return bitc::CAST_ZEXT;
556 case Instruction::SExt : return bitc::CAST_SEXT;
557 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
558 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
559 case Instruction::UIToFP : return bitc::CAST_UITOFP;
560 case Instruction::SIToFP : return bitc::CAST_SITOFP;
561 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
562 case Instruction::FPExt : return bitc::CAST_FPEXT;
563 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
564 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
565 case Instruction::BitCast : return bitc::CAST_BITCAST;
566 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
567 }
568}
569
570static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
571 switch (Opcode) {
572 default: llvm_unreachable("Unknown binary instruction!");
573 case Instruction::FNeg: return bitc::UNOP_FNEG;
574 }
575}
576
577static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
578 switch (Opcode) {
579 default: llvm_unreachable("Unknown binary instruction!");
580 case Instruction::Add:
581 case Instruction::FAdd: return bitc::BINOP_ADD;
582 case Instruction::Sub:
583 case Instruction::FSub: return bitc::BINOP_SUB;
584 case Instruction::Mul:
585 case Instruction::FMul: return bitc::BINOP_MUL;
586 case Instruction::UDiv: return bitc::BINOP_UDIV;
587 case Instruction::FDiv:
588 case Instruction::SDiv: return bitc::BINOP_SDIV;
589 case Instruction::URem: return bitc::BINOP_UREM;
590 case Instruction::FRem:
591 case Instruction::SRem: return bitc::BINOP_SREM;
592 case Instruction::Shl: return bitc::BINOP_SHL;
593 case Instruction::LShr: return bitc::BINOP_LSHR;
594 case Instruction::AShr: return bitc::BINOP_ASHR;
595 case Instruction::And: return bitc::BINOP_AND;
596 case Instruction::Or: return bitc::BINOP_OR;
597 case Instruction::Xor: return bitc::BINOP_XOR;
598 }
599}
600
602 switch (Op) {
603 default: llvm_unreachable("Unknown RMW operation!");
609 case AtomicRMWInst::Or: return bitc::RMW_OR;
620 return bitc::RMW_UINC_WRAP;
622 return bitc::RMW_UDEC_WRAP;
623 }
624}
625
626static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
627 switch (Ordering) {
628 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
629 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
630 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
631 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
632 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
633 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
634 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
635 }
636 llvm_unreachable("Invalid ordering");
637}
638
639static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
640 StringRef Str, unsigned AbbrevToUse) {
642
643 // Code: [strchar x N]
644 for (char C : Str) {
645 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
646 AbbrevToUse = 0;
647 Vals.push_back(C);
648 }
649
650 // Emit the finished record.
651 Stream.EmitRecord(Code, Vals, AbbrevToUse);
652}
653
655 switch (Kind) {
656 case Attribute::Alignment:
658 case Attribute::AllocAlign:
660 case Attribute::AllocSize:
662 case Attribute::AlwaysInline:
664 case Attribute::Builtin:
666 case Attribute::ByVal:
668 case Attribute::Convergent:
670 case Attribute::InAlloca:
672 case Attribute::Cold:
674 case Attribute::DisableSanitizerInstrumentation:
676 case Attribute::FnRetThunkExtern:
678 case Attribute::Hot:
679 return bitc::ATTR_KIND_HOT;
680 case Attribute::ElementType:
682 case Attribute::InlineHint:
684 case Attribute::InReg:
686 case Attribute::JumpTable:
688 case Attribute::MinSize:
690 case Attribute::AllocatedPointer:
692 case Attribute::AllocKind:
694 case Attribute::Memory:
696 case Attribute::NoFPClass:
698 case Attribute::Naked:
700 case Attribute::Nest:
702 case Attribute::NoAlias:
704 case Attribute::NoBuiltin:
706 case Attribute::NoCallback:
708 case Attribute::NoCapture:
710 case Attribute::NoDuplicate:
712 case Attribute::NoFree:
714 case Attribute::NoImplicitFloat:
716 case Attribute::NoInline:
718 case Attribute::NoRecurse:
720 case Attribute::NoMerge:
722 case Attribute::NonLazyBind:
724 case Attribute::NonNull:
726 case Attribute::Dereferenceable:
728 case Attribute::DereferenceableOrNull:
730 case Attribute::NoRedZone:
732 case Attribute::NoReturn:
734 case Attribute::NoSync:
736 case Attribute::NoCfCheck:
738 case Attribute::NoProfile:
740 case Attribute::SkipProfile:
742 case Attribute::NoUnwind:
744 case Attribute::NoSanitizeBounds:
746 case Attribute::NoSanitizeCoverage:
748 case Attribute::NullPointerIsValid:
750 case Attribute::OptForFuzzing:
752 case Attribute::OptimizeForSize:
754 case Attribute::OptimizeNone:
756 case Attribute::ReadNone:
758 case Attribute::ReadOnly:
760 case Attribute::Returned:
762 case Attribute::ReturnsTwice:
764 case Attribute::SExt:
766 case Attribute::Speculatable:
768 case Attribute::StackAlignment:
770 case Attribute::StackProtect:
772 case Attribute::StackProtectReq:
774 case Attribute::StackProtectStrong:
776 case Attribute::SafeStack:
778 case Attribute::ShadowCallStack:
780 case Attribute::StrictFP:
782 case Attribute::StructRet:
784 case Attribute::SanitizeAddress:
786 case Attribute::SanitizeHWAddress:
788 case Attribute::SanitizeThread:
790 case Attribute::SanitizeMemory:
792 case Attribute::SpeculativeLoadHardening:
794 case Attribute::SwiftError:
796 case Attribute::SwiftSelf:
798 case Attribute::SwiftAsync:
800 case Attribute::UWTable:
802 case Attribute::VScaleRange:
804 case Attribute::WillReturn:
806 case Attribute::WriteOnly:
808 case Attribute::ZExt:
810 case Attribute::ImmArg:
812 case Attribute::SanitizeMemTag:
814 case Attribute::Preallocated:
816 case Attribute::NoUndef:
818 case Attribute::ByRef:
820 case Attribute::MustProgress:
822 case Attribute::PresplitCoroutine:
825 llvm_unreachable("Can not encode end-attribute kinds marker.");
826 case Attribute::None:
827 llvm_unreachable("Can not encode none-attribute.");
830 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
831 }
832
833 llvm_unreachable("Trying to encode unknown attribute");
834}
835
836void ModuleBitcodeWriter::writeAttributeGroupTable() {
837 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
839 if (AttrGrps.empty()) return;
840
842
844 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
845 unsigned AttrListIndex = Pair.first;
846 AttributeSet AS = Pair.second;
847 Record.push_back(VE.getAttributeGroupID(Pair));
848 Record.push_back(AttrListIndex);
849
850 for (Attribute Attr : AS) {
851 if (Attr.isEnumAttribute()) {
852 Record.push_back(0);
853 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
854 } else if (Attr.isIntAttribute()) {
855 Record.push_back(1);
856 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
857 Record.push_back(Attr.getValueAsInt());
858 } else if (Attr.isStringAttribute()) {
859 StringRef Kind = Attr.getKindAsString();
860 StringRef Val = Attr.getValueAsString();
861
862 Record.push_back(Val.empty() ? 3 : 4);
863 Record.append(Kind.begin(), Kind.end());
864 Record.push_back(0);
865 if (!Val.empty()) {
866 Record.append(Val.begin(), Val.end());
867 Record.push_back(0);
868 }
869 } else {
870 assert(Attr.isTypeAttribute());
871 Type *Ty = Attr.getValueAsType();
872 Record.push_back(Ty ? 6 : 5);
873 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
874 if (Ty)
875 Record.push_back(VE.getTypeID(Attr.getValueAsType()));
876 }
877 }
878
880 Record.clear();
881 }
882
883 Stream.ExitBlock();
884}
885
886void ModuleBitcodeWriter::writeAttributeTable() {
887 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
888 if (Attrs.empty()) return;
889
891
893 for (const AttributeList &AL : Attrs) {
894 for (unsigned i : AL.indexes()) {
895 AttributeSet AS = AL.getAttributes(i);
896 if (AS.hasAttributes())
897 Record.push_back(VE.getAttributeGroupID({i, AS}));
898 }
899
901 Record.clear();
902 }
903
904 Stream.ExitBlock();
905}
906
907/// WriteTypeTable - Write out the type table for a module.
908void ModuleBitcodeWriter::writeTypeTable() {
909 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
910
911 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
913
915
916 // Abbrev for TYPE_CODE_OPAQUE_POINTER.
917 auto Abbv = std::make_shared<BitCodeAbbrev>();
919 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
920 unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
921
922 // Abbrev for TYPE_CODE_FUNCTION.
923 Abbv = std::make_shared<BitCodeAbbrev>();
925 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
927 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
928 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
929
930 // Abbrev for TYPE_CODE_STRUCT_ANON.
931 Abbv = std::make_shared<BitCodeAbbrev>();
933 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
935 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
936 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
937
938 // Abbrev for TYPE_CODE_STRUCT_NAME.
939 Abbv = std::make_shared<BitCodeAbbrev>();
943 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
944
945 // Abbrev for TYPE_CODE_STRUCT_NAMED.
946 Abbv = std::make_shared<BitCodeAbbrev>();
948 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
950 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
951 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
952
953 // Abbrev for TYPE_CODE_ARRAY.
954 Abbv = std::make_shared<BitCodeAbbrev>();
956 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
957 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
958 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
959
960 // Emit an entry count so the reader can reserve space.
961 TypeVals.push_back(TypeList.size());
962 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
963 TypeVals.clear();
964
965 // Loop over all of the types, emitting each in turn.
966 for (Type *T : TypeList) {
967 int AbbrevToUse = 0;
968 unsigned Code = 0;
969
970 switch (T->getTypeID()) {
985 // INTEGER: [width]
987 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
988 break;
989 case Type::PointerTyID: {
990 PointerType *PTy = cast<PointerType>(T);
991 unsigned AddressSpace = PTy->getAddressSpace();
992 // OPAQUE_POINTER: [address space]
994 TypeVals.push_back(AddressSpace);
995 if (AddressSpace == 0)
996 AbbrevToUse = OpaquePtrAbbrev;
997 break;
998 }
999 case Type::FunctionTyID: {
1000 FunctionType *FT = cast<FunctionType>(T);
1001 // FUNCTION: [isvararg, retty, paramty x N]
1003 TypeVals.push_back(FT->isVarArg());
1004 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
1005 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1006 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
1007 AbbrevToUse = FunctionAbbrev;
1008 break;
1009 }
1010 case Type::StructTyID: {
1011 StructType *ST = cast<StructType>(T);
1012 // STRUCT: [ispacked, eltty x N]
1013 TypeVals.push_back(ST->isPacked());
1014 // Output all of the element types.
1015 for (Type *ET : ST->elements())
1016 TypeVals.push_back(VE.getTypeID(ET));
1017
1018 if (ST->isLiteral()) {
1020 AbbrevToUse = StructAnonAbbrev;
1021 } else {
1022 if (ST->isOpaque()) {
1024 } else {
1026 AbbrevToUse = StructNamedAbbrev;
1027 }
1028
1029 // Emit the name if it is present.
1030 if (!ST->getName().empty())
1032 StructNameAbbrev);
1033 }
1034 break;
1035 }
1036 case Type::ArrayTyID: {
1037 ArrayType *AT = cast<ArrayType>(T);
1038 // ARRAY: [numelts, eltty]
1040 TypeVals.push_back(AT->getNumElements());
1041 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1042 AbbrevToUse = ArrayAbbrev;
1043 break;
1044 }
1047 VectorType *VT = cast<VectorType>(T);
1048 // VECTOR [numelts, eltty] or
1049 // [numelts, eltty, scalable]
1051 TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1052 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1053 if (isa<ScalableVectorType>(VT))
1054 TypeVals.push_back(true);
1055 break;
1056 }
1057 case Type::TargetExtTyID: {
1058 TargetExtType *TET = cast<TargetExtType>(T);
1061 StructNameAbbrev);
1062 TypeVals.push_back(TET->getNumTypeParameters());
1063 for (Type *InnerTy : TET->type_params())
1064 TypeVals.push_back(VE.getTypeID(InnerTy));
1065 for (unsigned IntParam : TET->int_params())
1066 TypeVals.push_back(IntParam);
1067 break;
1068 }
1070 llvm_unreachable("Typed pointers cannot be added to IR modules");
1071 }
1072
1073 // Emit the finished record.
1074 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1075 TypeVals.clear();
1076 }
1077
1078 Stream.ExitBlock();
1079}
1080
1081static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
1082 switch (Linkage) {
1084 return 0;
1086 return 16;
1088 return 2;
1090 return 3;
1092 return 18;
1094 return 7;
1096 return 8;
1098 return 9;
1100 return 17;
1102 return 19;
1104 return 12;
1105 }
1106 llvm_unreachable("Invalid linkage");
1107}
1108
1109static unsigned getEncodedLinkage(const GlobalValue &GV) {
1110 return getEncodedLinkage(GV.getLinkage());
1111}
1112
1114 uint64_t RawFlags = 0;
1115 RawFlags |= Flags.ReadNone;
1116 RawFlags |= (Flags.ReadOnly << 1);
1117 RawFlags |= (Flags.NoRecurse << 2);
1118 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1119 RawFlags |= (Flags.NoInline << 4);
1120 RawFlags |= (Flags.AlwaysInline << 5);
1121 RawFlags |= (Flags.NoUnwind << 6);
1122 RawFlags |= (Flags.MayThrow << 7);
1123 RawFlags |= (Flags.HasUnknownCall << 8);
1124 RawFlags |= (Flags.MustBeUnreachable << 9);
1125 return RawFlags;
1126}
1127
1128// Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1129// in BitcodeReader.cpp.
1131 uint64_t RawFlags = 0;
1132
1133 RawFlags |= Flags.NotEligibleToImport; // bool
1134 RawFlags |= (Flags.Live << 1);
1135 RawFlags |= (Flags.DSOLocal << 2);
1136 RawFlags |= (Flags.CanAutoHide << 3);
1137
1138 // Linkage don't need to be remapped at that time for the summary. Any future
1139 // change to the getEncodedLinkage() function will need to be taken into
1140 // account here as well.
1141 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1142
1143 RawFlags |= (Flags.Visibility << 8); // 2 bits
1144
1145 return RawFlags;
1146}
1147
1149 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1150 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1151 return RawFlags;
1152}
1153
1154static unsigned getEncodedVisibility(const GlobalValue &GV) {
1155 switch (GV.getVisibility()) {
1156 case GlobalValue::DefaultVisibility: return 0;
1157 case GlobalValue::HiddenVisibility: return 1;
1158 case GlobalValue::ProtectedVisibility: return 2;
1159 }
1160 llvm_unreachable("Invalid visibility");
1161}
1162
1163static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1164 switch (GV.getDLLStorageClass()) {
1165 case GlobalValue::DefaultStorageClass: return 0;
1168 }
1169 llvm_unreachable("Invalid DLL storage class");
1170}
1171
1172static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1173 switch (GV.getThreadLocalMode()) {
1174 case GlobalVariable::NotThreadLocal: return 0;
1175 case GlobalVariable::GeneralDynamicTLSModel: return 1;
1176 case GlobalVariable::LocalDynamicTLSModel: return 2;
1177 case GlobalVariable::InitialExecTLSModel: return 3;
1178 case GlobalVariable::LocalExecTLSModel: return 4;
1179 }
1180 llvm_unreachable("Invalid TLS model");
1181}
1182
1183static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1184 switch (C.getSelectionKind()) {
1185 case Comdat::Any:
1187 case Comdat::ExactMatch:
1189 case Comdat::Largest:
1193 case Comdat::SameSize:
1195 }
1196 llvm_unreachable("Invalid selection kind");
1197}
1198
1199static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1200 switch (GV.getUnnamedAddr()) {
1201 case GlobalValue::UnnamedAddr::None: return 0;
1202 case GlobalValue::UnnamedAddr::Local: return 2;
1203 case GlobalValue::UnnamedAddr::Global: return 1;
1204 }
1205 llvm_unreachable("Invalid unnamed_addr");
1206}
1207
1208size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1209 if (GenerateHash)
1210 Hasher.update(Str);
1211 return StrtabBuilder.add(Str);
1212}
1213
1214void ModuleBitcodeWriter::writeComdats() {
1216 for (const Comdat *C : VE.getComdats()) {
1217 // COMDAT: [strtab offset, strtab size, selection_kind]
1218 Vals.push_back(addToStrtab(C->getName()));
1219 Vals.push_back(C->getName().size());
1221 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1222 Vals.clear();
1223 }
1224}
1225
1226/// Write a record that will eventually hold the word offset of the
1227/// module-level VST. For now the offset is 0, which will be backpatched
1228/// after the real VST is written. Saves the bit offset to backpatch.
1229void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1230 // Write a placeholder value in for the offset of the real VST,
1231 // which is written after the function blocks so that it can include
1232 // the offset of each function. The placeholder offset will be
1233 // updated when the real VST is written.
1234 auto Abbv = std::make_shared<BitCodeAbbrev>();
1236 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1237 // hold the real VST offset. Must use fixed instead of VBR as we don't
1238 // know how many VBR chunks to reserve ahead of time.
1240 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1241
1242 // Emit the placeholder
1244 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1245
1246 // Compute and save the bit offset to the placeholder, which will be
1247 // patched when the real VST is written. We can simply subtract the 32-bit
1248 // fixed size from the current bit number to get the location to backpatch.
1249 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1250}
1251
1253
1254/// Determine the encoding to use for the given string name and length.
1256 bool isChar6 = true;
1257 for (char C : Str) {
1258 if (isChar6)
1259 isChar6 = BitCodeAbbrevOp::isChar6(C);
1260 if ((unsigned char)C & 128)
1261 // don't bother scanning the rest.
1262 return SE_Fixed8;
1263 }
1264 if (isChar6)
1265 return SE_Char6;
1266 return SE_Fixed7;
1267}
1268
1269static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
1270 "Sanitizer Metadata is too large for naive serialization.");
1271static unsigned
1273 return Meta.NoAddress | (Meta.NoHWAddress << 1) |
1274 (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
1275}
1276
1277/// Emit top-level description of module, including target triple, inline asm,
1278/// descriptors for global variables, and function prototype info.
1279/// Returns the bit offset to backpatch with the location of the real VST.
1280void ModuleBitcodeWriter::writeModuleInfo() {
1281 // Emit various pieces of data attached to a module.
1282 if (!M.getTargetTriple().empty())
1283 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1284 0 /*TODO*/);
1285 const std::string &DL = M.getDataLayoutStr();
1286 if (!DL.empty())
1288 if (!M.getModuleInlineAsm().empty())
1289 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1290 0 /*TODO*/);
1291
1292 // Emit information about sections and GC, computing how many there are. Also
1293 // compute the maximum alignment value.
1294 std::map<std::string, unsigned> SectionMap;
1295 std::map<std::string, unsigned> GCMap;
1296 MaybeAlign MaxAlignment;
1297 unsigned MaxGlobalType = 0;
1298 const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1299 if (A)
1300 MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1301 };
1302 for (const GlobalVariable &GV : M.globals()) {
1303 UpdateMaxAlignment(GV.getAlign());
1304 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1305 if (GV.hasSection()) {
1306 // Give section names unique ID's.
1307 unsigned &Entry = SectionMap[std::string(GV.getSection())];
1308 if (!Entry) {
1309 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1310 0 /*TODO*/);
1311 Entry = SectionMap.size();
1312 }
1313 }
1314 }
1315 for (const Function &F : M) {
1316 UpdateMaxAlignment(F.getAlign());
1317 if (F.hasSection()) {
1318 // Give section names unique ID's.
1319 unsigned &Entry = SectionMap[std::string(F.getSection())];
1320 if (!Entry) {
1322 0 /*TODO*/);
1323 Entry = SectionMap.size();
1324 }
1325 }
1326 if (F.hasGC()) {
1327 // Same for GC names.
1328 unsigned &Entry = GCMap[F.getGC()];
1329 if (!Entry) {
1331 0 /*TODO*/);
1332 Entry = GCMap.size();
1333 }
1334 }
1335 }
1336
1337 // Emit abbrev for globals, now that we know # sections and max alignment.
1338 unsigned SimpleGVarAbbrev = 0;
1339 if (!M.global_empty()) {
1340 // Add an abbrev for common globals with no visibility or thread localness.
1341 auto Abbv = std::make_shared<BitCodeAbbrev>();
1346 Log2_32_Ceil(MaxGlobalType+1)));
1347 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1348 //| explicitType << 1
1349 //| constant
1350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1352 if (!MaxAlignment) // Alignment.
1353 Abbv->Add(BitCodeAbbrevOp(0));
1354 else {
1355 unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
1357 Log2_32_Ceil(MaxEncAlignment+1)));
1358 }
1359 if (SectionMap.empty()) // Section.
1360 Abbv->Add(BitCodeAbbrevOp(0));
1361 else
1363 Log2_32_Ceil(SectionMap.size()+1)));
1364 // Don't bother emitting vis + thread local.
1365 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1366 }
1367
1369 // Emit the module's source file name.
1370 {
1371 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1373 if (Bits == SE_Char6)
1374 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1375 else if (Bits == SE_Fixed7)
1376 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1377
1378 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1379 auto Abbv = std::make_shared<BitCodeAbbrev>();
1382 Abbv->Add(AbbrevOpToUse);
1383 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1384
1385 for (const auto P : M.getSourceFileName())
1386 Vals.push_back((unsigned char)P);
1387
1388 // Emit the finished record.
1389 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1390 Vals.clear();
1391 }
1392
1393 // Emit the global variable information.
1394 for (const GlobalVariable &GV : M.globals()) {
1395 unsigned AbbrevToUse = 0;
1396
1397 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1398 // linkage, alignment, section, visibility, threadlocal,
1399 // unnamed_addr, externally_initialized, dllstorageclass,
1400 // comdat, attributes, DSO_Local, GlobalSanitizer]
1401 Vals.push_back(addToStrtab(GV.getName()));
1402 Vals.push_back(GV.getName().size());
1403 Vals.push_back(VE.getTypeID(GV.getValueType()));
1404 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1405 Vals.push_back(GV.isDeclaration() ? 0 :
1406 (VE.getValueID(GV.getInitializer()) + 1));
1407 Vals.push_back(getEncodedLinkage(GV));
1408 Vals.push_back(getEncodedAlign(GV.getAlign()));
1409 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1410 : 0);
1411 if (GV.isThreadLocal() ||
1412 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1413 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1414 GV.isExternallyInitialized() ||
1415 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1416 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1417 GV.hasPartition() || GV.hasSanitizerMetadata()) {
1421 Vals.push_back(GV.isExternallyInitialized());
1423 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1424
1425 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1426 Vals.push_back(VE.getAttributeListID(AL));
1427
1428 Vals.push_back(GV.isDSOLocal());
1429 Vals.push_back(addToStrtab(GV.getPartition()));
1430 Vals.push_back(GV.getPartition().size());
1431
1432 Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
1433 GV.getSanitizerMetadata())
1434 : 0));
1435 } else {
1436 AbbrevToUse = SimpleGVarAbbrev;
1437 }
1438
1439 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1440 Vals.clear();
1441 }
1442
1443 // Emit the function proto information.
1444 for (const Function &F : M) {
1445 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1446 // linkage, paramattrs, alignment, section, visibility, gc,
1447 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1448 // prefixdata, personalityfn, DSO_Local, addrspace]
1449 Vals.push_back(addToStrtab(F.getName()));
1450 Vals.push_back(F.getName().size());
1451 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1452 Vals.push_back(F.getCallingConv());
1453 Vals.push_back(F.isDeclaration());
1455 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1456 Vals.push_back(getEncodedAlign(F.getAlign()));
1457 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1458 : 0);
1460 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1462 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1463 : 0);
1465 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1466 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1467 : 0);
1468 Vals.push_back(
1469 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1470
1471 Vals.push_back(F.isDSOLocal());
1472 Vals.push_back(F.getAddressSpace());
1473 Vals.push_back(addToStrtab(F.getPartition()));
1474 Vals.push_back(F.getPartition().size());
1475
1476 unsigned AbbrevToUse = 0;
1477 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1478 Vals.clear();
1479 }
1480
1481 // Emit the alias information.
1482 for (const GlobalAlias &A : M.aliases()) {
1483 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1484 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1485 // DSO_Local]
1486 Vals.push_back(addToStrtab(A.getName()));
1487 Vals.push_back(A.getName().size());
1488 Vals.push_back(VE.getTypeID(A.getValueType()));
1489 Vals.push_back(A.getType()->getAddressSpace());
1490 Vals.push_back(VE.getValueID(A.getAliasee()));
1496 Vals.push_back(A.isDSOLocal());
1497 Vals.push_back(addToStrtab(A.getPartition()));
1498 Vals.push_back(A.getPartition().size());
1499
1500 unsigned AbbrevToUse = 0;
1501 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1502 Vals.clear();
1503 }
1504
1505 // Emit the ifunc information.
1506 for (const GlobalIFunc &I : M.ifuncs()) {
1507 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1508 // val#, linkage, visibility, DSO_Local]
1509 Vals.push_back(addToStrtab(I.getName()));
1510 Vals.push_back(I.getName().size());
1511 Vals.push_back(VE.getTypeID(I.getValueType()));
1512 Vals.push_back(I.getType()->getAddressSpace());
1513 Vals.push_back(VE.getValueID(I.getResolver()));
1516 Vals.push_back(I.isDSOLocal());
1517 Vals.push_back(addToStrtab(I.getPartition()));
1518 Vals.push_back(I.getPartition().size());
1519 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1520 Vals.clear();
1521 }
1522
1523 writeValueSymbolTableForwardDecl();
1524}
1525
1527 uint64_t Flags = 0;
1528
1529 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1530 if (OBO->hasNoSignedWrap())
1531 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1532 if (OBO->hasNoUnsignedWrap())
1533 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1534 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1535 if (PEO->isExact())
1536 Flags |= 1 << bitc::PEO_EXACT;
1537 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1538 if (FPMO->hasAllowReassoc())
1539 Flags |= bitc::AllowReassoc;
1540 if (FPMO->hasNoNaNs())
1541 Flags |= bitc::NoNaNs;
1542 if (FPMO->hasNoInfs())
1543 Flags |= bitc::NoInfs;
1544 if (FPMO->hasNoSignedZeros())
1545 Flags |= bitc::NoSignedZeros;
1546 if (FPMO->hasAllowReciprocal())
1547 Flags |= bitc::AllowReciprocal;
1548 if (FPMO->hasAllowContract())
1549 Flags |= bitc::AllowContract;
1550 if (FPMO->hasApproxFunc())
1551 Flags |= bitc::ApproxFunc;
1552 }
1553
1554 return Flags;
1555}
1556
1557void ModuleBitcodeWriter::writeValueAsMetadata(
1559 // Mimic an MDNode with a value as one operand.
1560 Value *V = MD->getValue();
1561 Record.push_back(VE.getTypeID(V->getType()));
1562 Record.push_back(VE.getValueID(V));
1564 Record.clear();
1565}
1566
1567void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1569 unsigned Abbrev) {
1570 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1571 Metadata *MD = N->getOperand(i);
1572 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1573 "Unexpected function-local metadata");
1574 Record.push_back(VE.getMetadataOrNullID(MD));
1575 }
1576 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1578 Record, Abbrev);
1579 Record.clear();
1580}
1581
1582unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1583 // Assume the column is usually under 128, and always output the inlined-at
1584 // location (it's never more expensive than building an array size 1).
1585 auto Abbv = std::make_shared<BitCodeAbbrev>();
1593 return Stream.EmitAbbrev(std::move(Abbv));
1594}
1595
1596void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1598 unsigned &Abbrev) {
1599 if (!Abbrev)
1600 Abbrev = createDILocationAbbrev();
1601
1602 Record.push_back(N->isDistinct());
1603 Record.push_back(N->getLine());
1604 Record.push_back(N->getColumn());
1605 Record.push_back(VE.getMetadataID(N->getScope()));
1606 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1607 Record.push_back(N->isImplicitCode());
1608
1609 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1610 Record.clear();
1611}
1612
1613unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1614 // Assume the column is usually under 128, and always output the inlined-at
1615 // location (it's never more expensive than building an array size 1).
1616 auto Abbv = std::make_shared<BitCodeAbbrev>();
1624 return Stream.EmitAbbrev(std::move(Abbv));
1625}
1626
1627void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1629 unsigned &Abbrev) {
1630 if (!Abbrev)
1631 Abbrev = createGenericDINodeAbbrev();
1632
1633 Record.push_back(N->isDistinct());
1634 Record.push_back(N->getTag());
1635 Record.push_back(0); // Per-tag version field; unused for now.
1636
1637 for (auto &I : N->operands())
1638 Record.push_back(VE.getMetadataOrNullID(I));
1639
1641 Record.clear();
1642}
1643
1644void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1646 unsigned Abbrev) {
1647 const uint64_t Version = 2 << 1;
1648 Record.push_back((uint64_t)N->isDistinct() | Version);
1649 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1650 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1651 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1652 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1653
1654 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1655 Record.clear();
1656}
1657
1658void ModuleBitcodeWriter::writeDIGenericSubrange(
1660 unsigned Abbrev) {
1661 Record.push_back((uint64_t)N->isDistinct());
1662 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1663 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1664 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1665 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1666
1668 Record.clear();
1669}
1670
1672 if ((int64_t)V >= 0)
1673 Vals.push_back(V << 1);
1674 else
1675 Vals.push_back((-V << 1) | 1);
1676}
1677
1679 // We have an arbitrary precision integer value to write whose
1680 // bit width is > 64. However, in canonical unsigned integer
1681 // format it is likely that the high bits are going to be zero.
1682 // So, we only write the number of active words.
1683 unsigned NumWords = A.getActiveWords();
1684 const uint64_t *RawData = A.getRawData();
1685 for (unsigned i = 0; i < NumWords; i++)
1686 emitSignedInt64(Vals, RawData[i]);
1687}
1688
1689void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1691 unsigned Abbrev) {
1692 const uint64_t IsBigInt = 1 << 2;
1693 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
1694 Record.push_back(N->getValue().getBitWidth());
1695 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1696 emitWideAPInt(Record, N->getValue());
1697
1699 Record.clear();
1700}
1701
1702void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1704 unsigned Abbrev) {
1705 Record.push_back(N->isDistinct());
1706 Record.push_back(N->getTag());
1707 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1708 Record.push_back(N->getSizeInBits());
1709 Record.push_back(N->getAlignInBits());
1710 Record.push_back(N->getEncoding());
1711 Record.push_back(N->getFlags());
1712
1714 Record.clear();
1715}
1716
1717void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
1719 unsigned Abbrev) {
1720 Record.push_back(N->isDistinct());
1721 Record.push_back(N->getTag());
1722 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1723 Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1724 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
1725 Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
1726 Record.push_back(N->getSizeInBits());
1727 Record.push_back(N->getAlignInBits());
1728 Record.push_back(N->getEncoding());
1729
1731 Record.clear();
1732}
1733
1734void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1736 unsigned Abbrev) {
1737 Record.push_back(N->isDistinct());
1738 Record.push_back(N->getTag());
1739 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1740 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1741 Record.push_back(N->getLine());
1742 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1743 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1744 Record.push_back(N->getSizeInBits());
1745 Record.push_back(N->getAlignInBits());
1746 Record.push_back(N->getOffsetInBits());
1747 Record.push_back(N->getFlags());
1748 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1749
1750 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1751 // that there is no DWARF address space associated with DIDerivedType.
1752 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1753 Record.push_back(*DWARFAddressSpace + 1);
1754 else
1755 Record.push_back(0);
1756
1757 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1758
1760 Record.clear();
1761}
1762
1763void ModuleBitcodeWriter::writeDICompositeType(
1765 unsigned Abbrev) {
1766 const unsigned IsNotUsedInOldTypeRef = 0x2;
1767 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1768 Record.push_back(N->getTag());
1769 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1770 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1771 Record.push_back(N->getLine());
1772 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1773 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1774 Record.push_back(N->getSizeInBits());
1775 Record.push_back(N->getAlignInBits());
1776 Record.push_back(N->getOffsetInBits());
1777 Record.push_back(N->getFlags());
1778 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1779 Record.push_back(N->getRuntimeLang());
1780 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1781 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1782 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1783 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
1784 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1785 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1786 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1787 Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
1788 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1789
1791 Record.clear();
1792}
1793
1794void ModuleBitcodeWriter::writeDISubroutineType(
1796 unsigned Abbrev) {
1797 const unsigned HasNoOldTypeRefs = 0x2;
1798 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1799 Record.push_back(N->getFlags());
1800 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1801 Record.push_back(N->getCC());
1802
1804 Record.clear();
1805}
1806
1807void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1809 unsigned Abbrev) {
1810 Record.push_back(N->isDistinct());
1811 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1812 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1813 if (N->getRawChecksum()) {
1814 Record.push_back(N->getRawChecksum()->Kind);
1815 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1816 } else {
1817 // Maintain backwards compatibility with the old internal representation of
1818 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1819 Record.push_back(0);
1820 Record.push_back(VE.getMetadataOrNullID(nullptr));
1821 }
1822 auto Source = N->getRawSource();
1823 if (Source)
1824 Record.push_back(VE.getMetadataOrNullID(Source));
1825
1826 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1827 Record.clear();
1828}
1829
1830void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1832 unsigned Abbrev) {
1833 assert(N->isDistinct() && "Expected distinct compile units");
1834 Record.push_back(/* IsDistinct */ true);
1835 Record.push_back(N->getSourceLanguage());
1836 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1837 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1838 Record.push_back(N->isOptimized());
1839 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1840 Record.push_back(N->getRuntimeVersion());
1841 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1842 Record.push_back(N->getEmissionKind());
1843 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1844 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1845 Record.push_back(/* subprograms */ 0);
1846 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1847 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1848 Record.push_back(N->getDWOId());
1849 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1850 Record.push_back(N->getSplitDebugInlining());
1851 Record.push_back(N->getDebugInfoForProfiling());
1852 Record.push_back((unsigned)N->getNameTableKind());
1853 Record.push_back(N->getRangesBaseAddress());
1854 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
1855 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
1856
1858 Record.clear();
1859}
1860
1861void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1863 unsigned Abbrev) {
1864 const uint64_t HasUnitFlag = 1 << 1;
1865 const uint64_t HasSPFlagsFlag = 1 << 2;
1866 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
1867 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1868 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1869 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1870 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1871 Record.push_back(N->getLine());
1872 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1873 Record.push_back(N->getScopeLine());
1874 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1875 Record.push_back(N->getSPFlags());
1876 Record.push_back(N->getVirtualIndex());
1877 Record.push_back(N->getFlags());
1878 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1879 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1880 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1881 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
1882 Record.push_back(N->getThisAdjustment());
1883 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1884 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1885 Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
1886
1888 Record.clear();
1889}
1890
1891void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1893 unsigned Abbrev) {
1894 Record.push_back(N->isDistinct());
1895 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1896 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1897 Record.push_back(N->getLine());
1898 Record.push_back(N->getColumn());
1899
1901 Record.clear();
1902}
1903
1904void ModuleBitcodeWriter::writeDILexicalBlockFile(
1906 unsigned Abbrev) {
1907 Record.push_back(N->isDistinct());
1908 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1909 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1910 Record.push_back(N->getDiscriminator());
1911
1913 Record.clear();
1914}
1915
1916void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
1918 unsigned Abbrev) {
1919 Record.push_back(N->isDistinct());
1920 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1921 Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
1922 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1923 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1924 Record.push_back(N->getLineNo());
1925
1927 Record.clear();
1928}
1929
1930void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1932 unsigned Abbrev) {
1933 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1934 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1935 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1936
1938 Record.clear();
1939}
1940
1941void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1943 unsigned Abbrev) {
1944 Record.push_back(N->isDistinct());
1945 Record.push_back(N->getMacinfoType());
1946 Record.push_back(N->getLine());
1947 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1948 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1949
1950 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1951 Record.clear();
1952}
1953
1954void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1956 unsigned Abbrev) {
1957 Record.push_back(N->isDistinct());
1958 Record.push_back(N->getMacinfoType());
1959 Record.push_back(N->getLine());
1960 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1961 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1962
1964 Record.clear();
1965}
1966
1967void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
1969 unsigned Abbrev) {
1970 Record.reserve(N->getArgs().size());
1971 for (ValueAsMetadata *MD : N->getArgs())
1972 Record.push_back(VE.getMetadataID(MD));
1973
1974 Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record, Abbrev);
1975 Record.clear();
1976}
1977
1978void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1980 unsigned Abbrev) {
1981 Record.push_back(N->isDistinct());
1982 for (auto &I : N->operands())
1983 Record.push_back(VE.getMetadataOrNullID(I));
1984 Record.push_back(N->getLineNo());
1985 Record.push_back(N->getIsDecl());
1986
1987 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1988 Record.clear();
1989}
1990
1991void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
1993 unsigned Abbrev) {
1994 // There are no arguments for this metadata type.
1995 Record.push_back(N->isDistinct());
1997 Record.clear();
1998}
1999
2000void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2002 unsigned Abbrev) {
2003 Record.push_back(N->isDistinct());
2004 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2005 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2006 Record.push_back(N->isDefault());
2007
2009 Record.clear();
2010}
2011
2012void ModuleBitcodeWriter::writeDITemplateValueParameter(
2014 unsigned Abbrev) {
2015 Record.push_back(N->isDistinct());
2016 Record.push_back(N->getTag());
2017 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2018 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2019 Record.push_back(N->isDefault());
2020 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
2021
2023 Record.clear();
2024}
2025
2026void ModuleBitcodeWriter::writeDIGlobalVariable(
2028 unsigned Abbrev) {
2029 const uint64_t Version = 2 << 1;
2030 Record.push_back((uint64_t)N->isDistinct() | Version);
2031 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2032 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2033 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2034 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2035 Record.push_back(N->getLine());
2036 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2037 Record.push_back(N->isLocalToUnit());
2038 Record.push_back(N->isDefinition());
2039 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
2040 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
2041 Record.push_back(N->getAlignInBits());
2042 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2043
2045 Record.clear();
2046}
2047
2048void ModuleBitcodeWriter::writeDILocalVariable(
2050 unsigned Abbrev) {
2051 // In order to support all possible bitcode formats in BitcodeReader we need
2052 // to distinguish the following cases:
2053 // 1) Record has no artificial tag (Record[1]),
2054 // has no obsolete inlinedAt field (Record[9]).
2055 // In this case Record size will be 8, HasAlignment flag is false.
2056 // 2) Record has artificial tag (Record[1]),
2057 // has no obsolete inlignedAt field (Record[9]).
2058 // In this case Record size will be 9, HasAlignment flag is false.
2059 // 3) Record has both artificial tag (Record[1]) and
2060 // obsolete inlignedAt field (Record[9]).
2061 // In this case Record size will be 10, HasAlignment flag is false.
2062 // 4) Record has neither artificial tag, nor inlignedAt field, but
2063 // HasAlignment flag is true and Record[8] contains alignment value.
2064 const uint64_t HasAlignmentFlag = 1 << 1;
2065 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2066 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2067 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2068 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2069 Record.push_back(N->getLine());
2070 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2071 Record.push_back(N->getArg());
2072 Record.push_back(N->getFlags());
2073 Record.push_back(N->getAlignInBits());
2074 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2075
2077 Record.clear();
2078}
2079
2080void ModuleBitcodeWriter::writeDILabel(
2082 unsigned Abbrev) {
2083 Record.push_back((uint64_t)N->isDistinct());
2084 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2085 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2086 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2087 Record.push_back(N->getLine());
2088
2089 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2090 Record.clear();
2091}
2092
2093void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
2095 unsigned Abbrev) {
2096 Record.reserve(N->getElements().size() + 1);
2097 const uint64_t Version = 3 << 1;
2098 Record.push_back((uint64_t)N->isDistinct() | Version);
2099 Record.append(N->elements_begin(), N->elements_end());
2100
2102 Record.clear();
2103}
2104
2105void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2107 unsigned Abbrev) {
2108 Record.push_back(N->isDistinct());
2109 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2110 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2111
2113 Record.clear();
2114}
2115
2116void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
2118 unsigned Abbrev) {
2119 Record.push_back(N->isDistinct());
2120 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2121 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2122 Record.push_back(N->getLine());
2123 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2124 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2125 Record.push_back(N->getAttributes());
2126 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2127
2129 Record.clear();
2130}
2131
2132void ModuleBitcodeWriter::writeDIImportedEntity(
2134 unsigned Abbrev) {
2135 Record.push_back(N->isDistinct());
2136 Record.push_back(N->getTag());
2137 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2138 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2139 Record.push_back(N->getLine());
2140 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2141 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2142 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2143
2145 Record.clear();
2146}
2147
2148unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2149 auto Abbv = std::make_shared<BitCodeAbbrev>();
2153 return Stream.EmitAbbrev(std::move(Abbv));
2154}
2155
2156void ModuleBitcodeWriter::writeNamedMetadata(
2158 if (M.named_metadata_empty())
2159 return;
2160
2161 unsigned Abbrev = createNamedMetadataAbbrev();
2162 for (const NamedMDNode &NMD : M.named_metadata()) {
2163 // Write name.
2164 StringRef Str = NMD.getName();
2165 Record.append(Str.bytes_begin(), Str.bytes_end());
2166 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2167 Record.clear();
2168
2169 // Write named metadata operands.
2170 for (const MDNode *N : NMD.operands())
2171 Record.push_back(VE.getMetadataID(N));
2173 Record.clear();
2174 }
2175}
2176
2177unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2178 auto Abbv = std::make_shared<BitCodeAbbrev>();
2180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2181 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2183 return Stream.EmitAbbrev(std::move(Abbv));
2184}
2185
2186/// Write out a record for MDString.
2187///
2188/// All the metadata strings in a metadata block are emitted in a single
2189/// record. The sizes and strings themselves are shoved into a blob.
2190void ModuleBitcodeWriter::writeMetadataStrings(
2192 if (Strings.empty())
2193 return;
2194
2195 // Start the record with the number of strings.
2196 Record.push_back(bitc::METADATA_STRINGS);
2197 Record.push_back(Strings.size());
2198
2199 // Emit the sizes of the strings in the blob.
2200 SmallString<256> Blob;
2201 {
2202 BitstreamWriter W(Blob);
2203 for (const Metadata *MD : Strings)
2204 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2205 W.FlushToWord();
2206 }
2207
2208 // Add the offset to the strings to the record.
2209 Record.push_back(Blob.size());
2210
2211 // Add the strings to the blob.
2212 for (const Metadata *MD : Strings)
2213 Blob.append(cast<MDString>(MD)->getString());
2214
2215 // Emit the final record.
2216 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2217 Record.clear();
2218}
2219
2220// Generates an enum to use as an index in the Abbrev array of Metadata record.
2221enum MetadataAbbrev : unsigned {
2222#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2223#include "llvm/IR/Metadata.def"
2226
2227void ModuleBitcodeWriter::writeMetadataRecords(
2229 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2230 if (MDs.empty())
2231 return;
2232
2233 // Initialize MDNode abbreviations.
2234#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2235#include "llvm/IR/Metadata.def"
2236
2237 for (const Metadata *MD : MDs) {
2238 if (IndexPos)
2239 IndexPos->push_back(Stream.GetCurrentBitNo());
2240 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2241 assert(N->isResolved() && "Expected forward references to be resolved");
2242
2243 switch (N->getMetadataID()) {
2244 default:
2245 llvm_unreachable("Invalid MDNode subclass");
2246#define HANDLE_MDNODE_LEAF(CLASS) \
2247 case Metadata::CLASS##Kind: \
2248 if (MDAbbrevs) \
2249 write##CLASS(cast<CLASS>(N), Record, \
2250 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2251 else \
2252 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2253 continue;
2254#include "llvm/IR/Metadata.def"
2255 }
2256 }
2257 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2258 }
2259}
2260
2261void ModuleBitcodeWriter::writeModuleMetadata() {
2262 if (!VE.hasMDs() && M.named_metadata_empty())
2263 return;
2264
2267
2268 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2269 // block and load any metadata.
2270 std::vector<unsigned> MDAbbrevs;
2271
2272 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2273 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2274 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2275 createGenericDINodeAbbrev();
2276
2277 auto Abbv = std::make_shared<BitCodeAbbrev>();
2281 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2282
2283 Abbv = std::make_shared<BitCodeAbbrev>();
2287 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2288
2289 // Emit MDStrings together upfront.
2290 writeMetadataStrings(VE.getMDStrings(), Record);
2291
2292 // We only emit an index for the metadata record if we have more than a given
2293 // (naive) threshold of metadatas, otherwise it is not worth it.
2294 if (VE.getNonMDStrings().size() > IndexThreshold) {
2295 // Write a placeholder value in for the offset of the metadata index,
2296 // which is written after the records, so that it can include
2297 // the offset of each entry. The placeholder offset will be
2298 // updated after all records are emitted.
2299 uint64_t Vals[] = {0, 0};
2300 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2301 }
2302
2303 // Compute and save the bit offset to the current position, which will be
2304 // patched when we emit the index later. We can simply subtract the 64-bit
2305 // fixed size from the current bit number to get the location to backpatch.
2306 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2307
2308 // This index will contain the bitpos for each individual record.
2309 std::vector<uint64_t> IndexPos;
2310 IndexPos.reserve(VE.getNonMDStrings().size());
2311
2312 // Write all the records
2313 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2314
2315 if (VE.getNonMDStrings().size() > IndexThreshold) {
2316 // Now that we have emitted all the records we will emit the index. But
2317 // first
2318 // backpatch the forward reference so that the reader can skip the records
2319 // efficiently.
2320 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2321 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2322
2323 // Delta encode the index.
2324 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2325 for (auto &Elt : IndexPos) {
2326 auto EltDelta = Elt - PreviousValue;
2327 PreviousValue = Elt;
2328 Elt = EltDelta;
2329 }
2330 // Emit the index record.
2331 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2332 IndexPos.clear();
2333 }
2334
2335 // Write the named metadata now.
2336 writeNamedMetadata(Record);
2337
2338 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2340 Record.push_back(VE.getValueID(&GO));
2341 pushGlobalMetadataAttachment(Record, GO);
2343 };
2344 for (const Function &F : M)
2345 if (F.isDeclaration() && F.hasMetadata())
2346 AddDeclAttachedMetadata(F);
2347 // FIXME: Only store metadata for declarations here, and move data for global
2348 // variable definitions to a separate block (PR28134).
2349 for (const GlobalVariable &GV : M.globals())
2350 if (GV.hasMetadata())
2351 AddDeclAttachedMetadata(GV);
2352
2353 Stream.ExitBlock();
2354}
2355
2356void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2357 if (!VE.hasMDs())
2358 return;
2359
2362 writeMetadataStrings(VE.getMDStrings(), Record);
2363 writeMetadataRecords(VE.getNonMDStrings(), Record);
2364 Stream.ExitBlock();
2365}
2366
2367void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2369 // [n x [id, mdnode]]
2371 GO.getAllMetadata(MDs);
2372 for (const auto &I : MDs) {
2373 Record.push_back(I.first);
2374 Record.push_back(VE.getMetadataID(I.second));
2375 }
2376}
2377
2378void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2380
2382
2383 if (F.hasMetadata()) {
2384 pushGlobalMetadataAttachment(Record, F);
2386 Record.clear();
2387 }
2388
2389 // Write metadata attachments
2390 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2392 for (const BasicBlock &BB : F)
2393 for (const Instruction &I : BB) {
2394 MDs.clear();
2395 I.getAllMetadataOtherThanDebugLoc(MDs);
2396
2397 // If no metadata, ignore instruction.
2398 if (MDs.empty()) continue;
2399
2400 Record.push_back(VE.getInstructionID(&I));
2401
2402 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2403 Record.push_back(MDs[i].first);
2404 Record.push_back(VE.getMetadataID(MDs[i].second));
2405 }
2407 Record.clear();
2408 }
2409
2410 Stream.ExitBlock();
2411}
2412
2413void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2415
2416 // Write metadata kinds
2417 // METADATA_KIND - [n x [id, name]]
2419 M.getMDKindNames(Names);
2420
2421 if (Names.empty()) return;
2422
2424
2425 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2426 Record.push_back(MDKindID);
2427 StringRef KName = Names[MDKindID];
2428 Record.append(KName.begin(), KName.end());
2429
2431 Record.clear();
2432 }
2433
2434 Stream.ExitBlock();
2435}
2436
2437void ModuleBitcodeWriter::writeOperandBundleTags() {
2438 // Write metadata kinds
2439 //
2440 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2441 //
2442 // OPERAND_BUNDLE_TAG - [strchr x N]
2443
2445 M.getOperandBundleTags(Tags);
2446
2447 if (Tags.empty())
2448 return;
2449
2451
2453
2454 for (auto Tag : Tags) {
2455 Record.append(Tag.begin(), Tag.end());
2456
2458 Record.clear();
2459 }
2460
2461 Stream.ExitBlock();
2462}
2463
2464void ModuleBitcodeWriter::writeSyncScopeNames() {
2466 M.getContext().getSyncScopeNames(SSNs);
2467 if (SSNs.empty())
2468 return;
2469
2471
2473 for (auto SSN : SSNs) {
2474 Record.append(SSN.begin(), SSN.end());
2476 Record.clear();
2477 }
2478
2479 Stream.ExitBlock();
2480}
2481
2482void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2483 bool isGlobal) {
2484 if (FirstVal == LastVal) return;
2485
2487
2488 unsigned AggregateAbbrev = 0;
2489 unsigned String8Abbrev = 0;
2490 unsigned CString7Abbrev = 0;
2491 unsigned CString6Abbrev = 0;
2492 // If this is a constant pool for the module, emit module-specific abbrevs.
2493 if (isGlobal) {
2494 // Abbrev for CST_CODE_AGGREGATE.
2495 auto Abbv = std::make_shared<BitCodeAbbrev>();
2498 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2499 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2500
2501 // Abbrev for CST_CODE_STRING.
2502 Abbv = std::make_shared<BitCodeAbbrev>();
2506 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2507 // Abbrev for CST_CODE_CSTRING.
2508 Abbv = std::make_shared<BitCodeAbbrev>();
2512 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2513 // Abbrev for CST_CODE_CSTRING.
2514 Abbv = std::make_shared<BitCodeAbbrev>();
2518 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2519 }
2520
2522
2523 const ValueEnumerator::ValueList &Vals = VE.getValues();
2524 Type *LastTy = nullptr;
2525 for (unsigned i = FirstVal; i != LastVal; ++i) {
2526 const Value *V = Vals[i].first;
2527 // If we need to switch types, do so now.
2528 if (V->getType() != LastTy) {
2529 LastTy = V->getType();
2530 Record.push_back(VE.getTypeID(LastTy));
2532 CONSTANTS_SETTYPE_ABBREV);
2533 Record.clear();
2534 }
2535
2536 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2537 Record.push_back(VE.getTypeID(IA->getFunctionType()));
2538 Record.push_back(
2539 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2540 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2541
2542 // Add the asm string.
2543 const std::string &AsmStr = IA->getAsmString();
2544 Record.push_back(AsmStr.size());
2545 Record.append(AsmStr.begin(), AsmStr.end());
2546
2547 // Add the constraint string.
2548 const std::string &ConstraintStr = IA->getConstraintString();
2549 Record.push_back(ConstraintStr.size());
2550 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2552 Record.clear();
2553 continue;
2554 }
2555 const Constant *C = cast<Constant>(V);
2556 unsigned Code = -1U;
2557 unsigned AbbrevToUse = 0;
2558 if (C->isNullValue()) {
2560 } else if (isa<PoisonValue>(C)) {
2562 } else if (isa<UndefValue>(C)) {
2564 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2565 if (IV->getBitWidth() <= 64) {
2566 uint64_t V = IV->getSExtValue();
2569 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2570 } else { // Wide integers, > 64 bits in size.
2571 emitWideAPInt(Record, IV->getValue());
2573 }
2574 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2576 Type *Ty = CFP->getType();
2577 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2578 Ty->isDoubleTy()) {
2579 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2580 } else if (Ty->isX86_FP80Ty()) {
2581 // api needed to prevent premature destruction
2582 // bits are not in the same order as a normal i80 APInt, compensate.
2583 APInt api = CFP->getValueAPF().bitcastToAPInt();
2584 const uint64_t *p = api.getRawData();
2585 Record.push_back((p[1] << 48) | (p[0] >> 16));
2586 Record.push_back(p[0] & 0xffffLL);
2587 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2588 APInt api = CFP->getValueAPF().bitcastToAPInt();
2589 const uint64_t *p = api.getRawData();
2590 Record.push_back(p[0]);
2591 Record.push_back(p[1]);
2592 } else {
2593 assert(0 && "Unknown FP type!");
2594 }
2595 } else if (isa<ConstantDataSequential>(C) &&
2596 cast<ConstantDataSequential>(C)->isString()) {
2597 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2598 // Emit constant strings specially.
2599 unsigned NumElts = Str->getNumElements();
2600 // If this is a null-terminated string, use the denser CSTRING encoding.
2601 if (Str->isCString()) {
2603 --NumElts; // Don't encode the null, which isn't allowed by char6.
2604 } else {
2606 AbbrevToUse = String8Abbrev;
2607 }
2608 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2609 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2610 for (unsigned i = 0; i != NumElts; ++i) {
2611 unsigned char V = Str->getElementAsInteger(i);
2612 Record.push_back(V);
2613 isCStr7 &= (V & 128) == 0;
2614 if (isCStrChar6)
2615 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2616 }
2617
2618 if (isCStrChar6)
2619 AbbrevToUse = CString6Abbrev;
2620 else if (isCStr7)
2621 AbbrevToUse = CString7Abbrev;
2622 } else if (const ConstantDataSequential *CDS =
2623 dyn_cast<ConstantDataSequential>(C)) {
2625 Type *EltTy = CDS->getElementType();
2626 if (isa<IntegerType>(EltTy)) {
2627 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2628 Record.push_back(CDS->getElementAsInteger(i));
2629 } else {
2630 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2631 Record.push_back(
2632 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2633 }
2634 } else if (isa<ConstantAggregate>(C)) {
2636 for (const Value *Op : C->operands())
2637 Record.push_back(VE.getValueID(Op));
2638 AbbrevToUse = AggregateAbbrev;
2639 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2640 switch (CE->getOpcode()) {
2641 default:
2642 if (Instruction::isCast(CE->getOpcode())) {
2644 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2645 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2646 Record.push_back(VE.getValueID(C->getOperand(0)));
2647 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2648 } else {
2649 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2651 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2652 Record.push_back(VE.getValueID(C->getOperand(0)));
2653 Record.push_back(VE.getValueID(C->getOperand(1)));
2655 if (Flags != 0)
2656 Record.push_back(Flags);
2657 }
2658 break;
2659 case Instruction::FNeg: {
2660 assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2662 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2663 Record.push_back(VE.getValueID(C->getOperand(0)));
2665 if (Flags != 0)
2666 Record.push_back(Flags);
2667 break;
2668 }
2669 case Instruction::GetElementPtr: {
2671 const auto *GO = cast<GEPOperator>(C);
2672 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2673 if (std::optional<unsigned> Idx = GO->getInRangeIndex()) {
2675 Record.push_back((*Idx << 1) | GO->isInBounds());
2676 } else if (GO->isInBounds())
2678 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2679 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2680 Record.push_back(VE.getValueID(C->getOperand(i)));
2681 }
2682 break;
2683 }
2684 case Instruction::ExtractElement:
2686 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2687 Record.push_back(VE.getValueID(C->getOperand(0)));
2688 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2689 Record.push_back(VE.getValueID(C->getOperand(1)));
2690 break;
2691 case Instruction::InsertElement:
2693 Record.push_back(VE.getValueID(C->getOperand(0)));
2694 Record.push_back(VE.getValueID(C->getOperand(1)));
2695 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2696 Record.push_back(VE.getValueID(C->getOperand(2)));
2697 break;
2698 case Instruction::ShuffleVector:
2699 // If the return type and argument types are the same, this is a
2700 // standard shufflevector instruction. If the types are different,
2701 // then the shuffle is widening or truncating the input vectors, and
2702 // the argument type must also be encoded.
2703 if (C->getType() == C->getOperand(0)->getType()) {
2705 } else {
2707 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2708 }
2709 Record.push_back(VE.getValueID(C->getOperand(0)));
2710 Record.push_back(VE.getValueID(C->getOperand(1)));
2711 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
2712 break;
2713 case Instruction::ICmp:
2714 case Instruction::FCmp:
2716 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2717 Record.push_back(VE.getValueID(C->getOperand(0)));
2718 Record.push_back(VE.getValueID(C->getOperand(1)));
2719 Record.push_back(CE->getPredicate());
2720 break;
2721 }
2722 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2724 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2725 Record.push_back(VE.getValueID(BA->getFunction()));
2726 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2727 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2729 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2730 Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
2731 } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
2733 Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
2734 Record.push_back(VE.getValueID(NC->getGlobalValue()));
2735 } else {
2736#ifndef NDEBUG
2737 C->dump();
2738#endif
2739 llvm_unreachable("Unknown constant!");
2740 }
2741 Stream.EmitRecord(Code, Record, AbbrevToUse);
2742 Record.clear();
2743 }
2744
2745 Stream.ExitBlock();
2746}
2747
2748void ModuleBitcodeWriter::writeModuleConstants() {
2749 const ValueEnumerator::ValueList &Vals = VE.getValues();
2750
2751 // Find the first constant to emit, which is the first non-globalvalue value.
2752 // We know globalvalues have been emitted by WriteModuleInfo.
2753 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2754 if (!isa<GlobalValue>(Vals[i].first)) {
2755 writeConstants(i, Vals.size(), true);
2756 return;
2757 }
2758 }
2759}
2760
2761/// pushValueAndType - The file has to encode both the value and type id for
2762/// many values, because we need to know what type to create for forward
2763/// references. However, most operands are not forward references, so this type
2764/// field is not needed.
2765///
2766/// This function adds V's value ID to Vals. If the value ID is higher than the
2767/// instruction ID, then it is a forward reference, and it also includes the
2768/// type ID. The value ID that is written is encoded relative to the InstID.
2769bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2771 unsigned ValID = VE.getValueID(V);
2772 // Make encoding relative to the InstID.
2773 Vals.push_back(InstID - ValID);
2774 if (ValID >= InstID) {
2775 Vals.push_back(VE.getTypeID(V->getType()));
2776 return true;
2777 }
2778 return false;
2779}
2780
2781void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
2782 unsigned InstID) {
2784 LLVMContext &C = CS.getContext();
2785
2786 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2787 const auto &Bundle = CS.getOperandBundleAt(i);
2788 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2789
2790 for (auto &Input : Bundle.Inputs)
2791 pushValueAndType(Input, InstID, Record);
2792
2794 Record.clear();
2795 }
2796}
2797
2798/// pushValue - Like pushValueAndType, but where the type of the value is
2799/// omitted (perhaps it was already encoded in an earlier operand).
2800void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2802 unsigned ValID = VE.getValueID(V);
2803 Vals.push_back(InstID - ValID);
2804}
2805
2806void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2808 unsigned ValID = VE.getValueID(V);
2809 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2810 emitSignedInt64(Vals, diff);
2811}
2812
2813/// WriteInstruction - Emit an instruction to the specified stream.
2814void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2815 unsigned InstID,
2817 unsigned Code = 0;
2818 unsigned AbbrevToUse = 0;
2819 VE.setInstructionID(&I);
2820 switch (I.getOpcode()) {
2821 default:
2822 if (Instruction::isCast(I.getOpcode())) {
2824 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2825 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2826 Vals.push_back(VE.getTypeID(I.getType()));
2827 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2828 } else {
2829 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2831 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2832 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2833 pushValue(I.getOperand(1), InstID, Vals);
2834 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2836 if (Flags != 0) {
2837 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2838 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2839 Vals.push_back(Flags);
2840 }
2841 }
2842 break;
2843 case Instruction::FNeg: {
2845 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2846 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2847 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2849 if (Flags != 0) {
2850 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2851 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2852 Vals.push_back(Flags);
2853 }
2854 break;
2855 }
2856 case Instruction::GetElementPtr: {
2858 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2859 auto &GEPInst = cast<GetElementPtrInst>(I);
2860 Vals.push_back(GEPInst.isInBounds());
2861 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2862 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2863 pushValueAndType(I.getOperand(i), InstID, Vals);
2864 break;
2865 }
2866 case Instruction::ExtractValue: {
2868 pushValueAndType(I.getOperand(0), InstID, Vals);
2869 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2870 Vals.append(EVI->idx_begin(), EVI->idx_end());
2871 break;
2872 }
2873 case Instruction::InsertValue: {
2875 pushValueAndType(I.getOperand(0), InstID, Vals);
2876 pushValueAndType(I.getOperand(1), InstID, Vals);
2877 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2878 Vals.append(IVI->idx_begin(), IVI->idx_end());
2879 break;
2880 }
2881 case Instruction::Select: {
2883 pushValueAndType(I.getOperand(1), InstID, Vals);
2884 pushValue(I.getOperand(2), InstID, Vals);
2885 pushValueAndType(I.getOperand(0), InstID, Vals);
2887 if (Flags != 0)
2888 Vals.push_back(Flags);
2889 break;
2890 }
2891 case Instruction::ExtractElement:
2893 pushValueAndType(I.getOperand(0), InstID, Vals);
2894 pushValueAndType(I.getOperand(1), InstID, Vals);
2895 break;
2896 case Instruction::InsertElement:
2898 pushValueAndType(I.getOperand(0), InstID, Vals);
2899 pushValue(I.getOperand(1), InstID, Vals);
2900 pushValueAndType(I.getOperand(2), InstID, Vals);
2901 break;
2902 case Instruction::ShuffleVector:
2904 pushValueAndType(I.getOperand(0), InstID, Vals);
2905 pushValue(I.getOperand(1), InstID, Vals);
2906 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
2907 Vals);
2908 break;
2909 case Instruction::ICmp:
2910 case Instruction::FCmp: {
2911 // compare returning Int1Ty or vector of Int1Ty
2913 pushValueAndType(I.getOperand(0), InstID, Vals);
2914 pushValue(I.getOperand(1), InstID, Vals);
2915 Vals.push_back(cast<CmpInst>(I).getPredicate());
2917 if (Flags != 0)
2918 Vals.push_back(Flags);
2919 break;
2920 }
2921
2922 case Instruction::Ret:
2923 {
2925 unsigned NumOperands = I.getNumOperands();
2926 if (NumOperands == 0)
2927 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2928 else if (NumOperands == 1) {
2929 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2930 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2931 } else {
2932 for (unsigned i = 0, e = NumOperands; i != e; ++i)
2933 pushValueAndType(I.getOperand(i), InstID, Vals);
2934 }
2935 }
2936 break;
2937 case Instruction::Br:
2938 {
2940 const BranchInst &II = cast<BranchInst>(I);
2941 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2942 if (II.isConditional()) {
2943 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2944 pushValue(II.getCondition(), InstID, Vals);
2945 }
2946 }
2947 break;
2948 case Instruction::Switch:
2949 {
2951 const SwitchInst &SI = cast<SwitchInst>(I);
2952 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2953 pushValue(SI.getCondition(), InstID, Vals);
2954 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2955 for (auto Case : SI.cases()) {
2956 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2957 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2958 }
2959 }
2960 break;
2961 case Instruction::IndirectBr:
2963 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2964 // Encode the address operand as relative, but not the basic blocks.
2965 pushValue(I.getOperand(0), InstID, Vals);
2966 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2967 Vals.push_back(VE.getValueID(I.getOperand(i)));
2968 break;
2969
2970 case Instruction::Invoke: {
2971 const InvokeInst *II = cast<InvokeInst>(&I);
2972 const Value *Callee = II->getCalledOperand();
2973 FunctionType *FTy = II->getFunctionType();
2974
2975 if (II->hasOperandBundles())
2976 writeOperandBundles(*II, InstID);
2977
2979
2981 Vals.push_back(II->getCallingConv() | 1 << 13);
2982 Vals.push_back(VE.getValueID(II->getNormalDest()));
2983 Vals.push_back(VE.getValueID(II->getUnwindDest()));
2984 Vals.push_back(VE.getTypeID(FTy));
2985 pushValueAndType(Callee, InstID, Vals);
2986
2987 // Emit value #'s for the fixed parameters.
2988 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2989 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2990
2991 // Emit type/value pairs for varargs params.
2992 if (FTy->isVarArg()) {
2993 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
2994 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2995 }
2996 break;
2997 }
2998 case Instruction::Resume:
3000 pushValueAndType(I.getOperand(0), InstID, Vals);
3001 break;
3002 case Instruction::CleanupRet: {
3004 const auto &CRI = cast<CleanupReturnInst>(I);
3005 pushValue(CRI.getCleanupPad(), InstID, Vals);
3006 if (CRI.hasUnwindDest())
3007 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
3008 break;
3009 }
3010 case Instruction::CatchRet: {
3012 const auto &CRI = cast<CatchReturnInst>(I);
3013 pushValue(CRI.getCatchPad(), InstID, Vals);
3014 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
3015 break;
3016 }
3017 case Instruction::CleanupPad:
3018 case Instruction::CatchPad: {
3019 const auto &FuncletPad = cast<FuncletPadInst>(I);
3020 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
3022 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3023
3024 unsigned NumArgOperands = FuncletPad.arg_size();
3025 Vals.push_back(NumArgOperands);
3026 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
3027 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
3028 break;
3029 }
3030 case Instruction::CatchSwitch: {
3032 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
3033
3034 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3035
3036 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3037 Vals.push_back(NumHandlers);
3038 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3039 Vals.push_back(VE.getValueID(CatchPadBB));
3040
3041 if (CatchSwitch.hasUnwindDest())
3042 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3043 break;
3044 }
3045 case Instruction::CallBr: {
3046 const CallBrInst *CBI = cast<CallBrInst>(&I);
3047 const Value *Callee = CBI->getCalledOperand();
3048 FunctionType *FTy = CBI->getFunctionType();
3049
3050 if (CBI->hasOperandBundles())
3051 writeOperandBundles(*CBI, InstID);
3052
3054
3056
3059
3060 Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3061 Vals.push_back(CBI->getNumIndirectDests());
3062 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3063 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3064
3065 Vals.push_back(VE.getTypeID(FTy));
3066 pushValueAndType(Callee, InstID, Vals);
3067
3068 // Emit value #'s for the fixed parameters.
3069 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3070 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3071
3072 // Emit type/value pairs for varargs params.
3073 if (FTy->isVarArg()) {
3074 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3075 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3076 }
3077 break;
3078 }
3079 case Instruction::Unreachable:
3081 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3082 break;
3083
3084 case Instruction::PHI: {
3085 const PHINode &PN = cast<PHINode>(I);
3087 // With the newer instruction encoding, forward references could give
3088 // negative valued IDs. This is most common for PHIs, so we use
3089 // signed VBRs.
3091 Vals64.push_back(VE.getTypeID(PN.getType()));
3092 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3093 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3094 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3095 }
3096
3098 if (Flags != 0)
3099 Vals64.push_back(Flags);
3100
3101 // Emit a Vals64 vector and exit.
3102 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3103 Vals64.clear();
3104 return;
3105 }
3106
3107 case Instruction::LandingPad: {
3108 const LandingPadInst &LP = cast<LandingPadInst>(I);
3110 Vals.push_back(VE.getTypeID(LP.getType()));
3111 Vals.push_back(LP.isCleanup());
3112 Vals.push_back(LP.getNumClauses());
3113 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3114 if (LP.isCatch(I))
3116 else
3118 pushValueAndType(LP.getClause(I), InstID, Vals);
3119 }
3120 break;
3121 }
3122
3123 case Instruction::Alloca: {
3125 const AllocaInst &AI = cast<AllocaInst>(I);
3126 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3127 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3128 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3129 using APV = AllocaPackedValues;
3130 unsigned Record = 0;
3131 unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3132 Bitfield::set<APV::AlignLower>(
3133 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3134 Bitfield::set<APV::AlignUpper>(Record,
3135 EncodedAlign >> APV::AlignLower::Bits);
3136 Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3137 Bitfield::set<APV::ExplicitType>(Record, true);
3138 Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3139 Vals.push_back(Record);
3140
3141 unsigned AS = AI.getAddressSpace();
3142 if (AS != M.getDataLayout().getAllocaAddrSpace())
3143 Vals.push_back(AS);
3144 break;
3145 }
3146
3147 case Instruction::Load:
3148 if (cast<LoadInst>(I).isAtomic()) {
3150 pushValueAndType(I.getOperand(0), InstID, Vals);
3151 } else {
3153 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3154 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3155 }
3156 Vals.push_back(VE.getTypeID(I.getType()));
3157 Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3158 Vals.push_back(cast<LoadInst>(I).isVolatile());
3159 if (cast<LoadInst>(I).isAtomic()) {
3160 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3161 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3162 }
3163 break;
3164 case Instruction::Store:
3165 if (cast<StoreInst>(I).isAtomic())
3167 else
3169 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
3170 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3171 Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3172 Vals.push_back(cast<StoreInst>(I).isVolatile());
3173 if (cast<StoreInst>(I).isAtomic()) {
3174 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3175 Vals.push_back(
3176 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3177 }
3178 break;
3179 case Instruction::AtomicCmpXchg:
3181 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3182 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3183 pushValue(I.getOperand(2), InstID, Vals); // newval.
3184 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3185 Vals.push_back(
3186 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3187 Vals.push_back(
3188 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3189 Vals.push_back(
3190 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3191 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3192 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3193 break;
3194 case Instruction::AtomicRMW:
3196 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3197 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3198 Vals.push_back(
3199 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
3200 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3201 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3202 Vals.push_back(
3203 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3204 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3205 break;
3206 case Instruction::Fence:
3208 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3209 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3210 break;
3211 case Instruction::Call: {
3212 const CallInst &CI = cast<CallInst>(I);
3213 FunctionType *FTy = CI.getFunctionType();
3214
3215 if (CI.hasOperandBundles())
3216 writeOperandBundles(CI, InstID);
3217
3219
3221
3222 unsigned Flags = getOptimizationFlags(&I);
3224 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3225 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3227 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3228 unsigned(Flags != 0) << bitc::CALL_FMF);
3229 if (Flags != 0)
3230 Vals.push_back(Flags);
3231
3232 Vals.push_back(VE.getTypeID(FTy));
3233 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3234
3235 // Emit value #'s for the fixed parameters.
3236 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3237 // Check for labels (can happen with asm labels).
3238 if (FTy->getParamType(i)->isLabelTy())
3239 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
3240 else
3241 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3242 }
3243
3244 // Emit type/value pairs for varargs params.
3245 if (FTy->isVarArg()) {
3246 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3247 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3248 }
3249 break;
3250 }
3251 case Instruction::VAArg:
3253 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3254 pushValue(I.getOperand(0), InstID, Vals); // valist.
3255 Vals.push_back(VE.getTypeID(I.getType())); // restype.
3256 break;
3257 case Instruction::Freeze:
3259 pushValueAndType(I.getOperand(0), InstID, Vals);
3260 break;
3261 }
3262
3263 Stream.EmitRecord(Code, Vals, AbbrevToUse);
3264 Vals.clear();
3265}
3266
3267/// Write a GlobalValue VST to the module. The purpose of this data structure is
3268/// to allow clients to efficiently find the function body.
3269void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3270 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3271 // Get the offset of the VST we are writing, and backpatch it into
3272 // the VST forward declaration record.
3273 uint64_t VSTOffset = Stream.GetCurrentBitNo();
3274 // The BitcodeStartBit was the stream offset of the identification block.
3275 VSTOffset -= bitcodeStartBit();
3276 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3277 // Note that we add 1 here because the offset is relative to one word
3278 // before the start of the identification block, which was historically
3279 // always the start of the regular bitcode header.
3280 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3281
3283
3284 auto Abbv = std::make_shared<BitCodeAbbrev>();
3286 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3287 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3288 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3289
3290 for (const Function &F : M) {
3291 uint64_t Record[2];
3292
3293 if (F.isDeclaration())
3294 continue;
3295
3296 Record[0] = VE.getValueID(&F);
3297
3298 // Save the word offset of the function (from the start of the
3299 // actual bitcode written to the stream).
3300 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3301 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3302 // Note that we add 1 here because the offset is relative to one word
3303 // before the start of the identification block, which was historically
3304 // always the start of the regular bitcode header.
3305 Record[1] = BitcodeIndex / 32 + 1;
3306
3307 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3308 }
3309
3310 Stream.ExitBlock();
3311}
3312
3313/// Emit names for arguments, instructions and basic blocks in a function.
3314void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3315 const ValueSymbolTable &VST) {
3316 if (VST.empty())
3317 return;
3318
3320
3321 // FIXME: Set up the abbrev, we know how many values there are!
3322 // FIXME: We know if the type names can use 7-bit ascii.
3324
3325 for (const ValueName &Name : VST) {
3326 // Figure out the encoding to use for the name.
3328
3329 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3330 NameVals.push_back(VE.getValueID(Name.getValue()));
3331
3332 // VST_CODE_ENTRY: [valueid, namechar x N]
3333 // VST_CODE_BBENTRY: [bbid, namechar x N]
3334 unsigned Code;
3335 if (isa<BasicBlock>(Name.getValue())) {
3337 if (Bits == SE_Char6)
3338 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3339 } else {
3341 if (Bits == SE_Char6)
3342 AbbrevToUse = VST_ENTRY_6_ABBREV;
3343 else if (Bits == SE_Fixed7)
3344 AbbrevToUse = VST_ENTRY_7_ABBREV;
3345 }
3346
3347 for (const auto P : Name.getKey())
3348 NameVals.push_back((unsigned char)P);
3349
3350 // Emit the finished record.
3351 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3352 NameVals.clear();
3353 }
3354
3355 Stream.ExitBlock();
3356}
3357
3358void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3359 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3360 unsigned Code;
3361 if (isa<BasicBlock>(Order.V))
3363 else
3365
3366 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3367 Record.push_back(VE.getValueID(Order.V));
3368 Stream.EmitRecord(Code, Record);
3369}
3370
3371void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3373 "Expected to be preserving use-list order");
3374
3375 auto hasMore = [&]() {
3376 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3377 };
3378 if (!hasMore())
3379 // Nothing to do.
3380 return;
3381
3383 while (hasMore()) {
3384 writeUseList(std::move(VE.UseListOrders.back()));
3385 VE.UseListOrders.pop_back();
3386 }
3387 Stream.ExitBlock();
3388}
3389
3390/// Emit a function body to the module stream.
3391void ModuleBitcodeWriter::writeFunction(
3392 const Function &F,
3393 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3394 // Save the bitcode index of the start of this function block for recording
3395 // in the VST.
3396 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3397
3400
3402
3403 // Emit the number of basic blocks, so the reader can create them ahead of
3404 // time.
3405 Vals.push_back(VE.getBasicBlocks().size());
3407 Vals.clear();
3408
3409 // If there are function-local constants, emit them now.
3410 unsigned CstStart, CstEnd;
3411 VE.getFunctionConstantRange(CstStart, CstEnd);
3412 writeConstants(CstStart, CstEnd, false);
3413
3414 // If there is function-local metadata, emit it now.
3415 writeFunctionMetadata(F);
3416
3417 // Keep a running idea of what the instruction ID is.
3418 unsigned InstID = CstEnd;
3419
3420 bool NeedsMetadataAttachment = F.hasMetadata();
3421
3422 DILocation *LastDL = nullptr;
3423 SmallSetVector<Function *, 4> BlockAddressUsers;
3424
3425 // Finally, emit all the instructions, in order.
3426 for (const BasicBlock &BB : F) {
3427 for (const Instruction &I : BB) {
3428 writeInstruction(I, InstID, Vals);
3429
3430 if (!I.getType()->isVoidTy())
3431 ++InstID;
3432
3433 // If the instruction has metadata, write a metadata attachment later.
3434 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3435
3436 // If the instruction has a debug location, emit it.
3437 DILocation *DL = I.getDebugLoc();
3438 if (!DL)
3439 continue;
3440
3441 if (DL == LastDL) {
3442 // Just repeat the same debug loc as last time.
3444 continue;
3445 }
3446
3447 Vals.push_back(DL->getLine());
3448 Vals.push_back(DL->getColumn());
3449 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3450 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3451 Vals.push_back(DL->isImplicitCode());
3453 Vals.clear();
3454
3455 LastDL = DL;
3456 }
3457
3458 if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
3459 SmallVector<Value *> Worklist{BA};
3460 SmallPtrSet<Value *, 8> Visited{BA};
3461 while (!Worklist.empty()) {
3462 Value *V = Worklist.pop_back_val();
3463 for (User *U : V->users()) {
3464 if (auto *I = dyn_cast<Instruction>(U)) {
3465 Function *P = I->getFunction();
3466 if (P != &F)
3467 BlockAddressUsers.insert(P);
3468 } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
3469 Visited.insert(U).second)
3470 Worklist.push_back(U);
3471 }
3472 }
3473 }
3474 }
3475
3476 if (!BlockAddressUsers.empty()) {
3477 Vals.resize(BlockAddressUsers.size());
3478 for (auto I : llvm::enumerate(BlockAddressUsers))
3479 Vals[I.index()] = VE.getValueID(I.value());
3481 Vals.clear();
3482 }
3483
3484 // Emit names for all the instructions etc.
3485 if (auto *Symtab = F.getValueSymbolTable())
3486 writeFunctionLevelValueSymbolTable(*Symtab);
3487
3488 if (NeedsMetadataAttachment)
3489 writeFunctionMetadataAttachment(F);
3491 writeUseListBlock(&F);
3492 VE.purgeFunction();
3493 Stream.ExitBlock();
3494}
3495
3496// Emit blockinfo, which defines the standard abbreviations etc.
3497void ModuleBitcodeWriter::writeBlockInfo() {
3498 // We only want to emit block info records for blocks that have multiple
3499 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3500 // Other blocks can define their abbrevs inline.
3501 Stream.EnterBlockInfoBlock();
3502
3503 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3504 auto Abbv = std::make_shared<BitCodeAbbrev>();
3510 VST_ENTRY_8_ABBREV)
3511 llvm_unreachable("Unexpected abbrev ordering!");
3512 }
3513
3514 { // 7-bit fixed width VST_CODE_ENTRY strings.
3515 auto Abbv = std::make_shared<BitCodeAbbrev>();
3521 VST_ENTRY_7_ABBREV)
3522 llvm_unreachable("Unexpected abbrev ordering!");
3523 }
3524 { // 6-bit char6 VST_CODE_ENTRY strings.
3525 auto Abbv = std::make_shared<BitCodeAbbrev>();
3531 VST_ENTRY_6_ABBREV)
3532 llvm_unreachable("Unexpected abbrev ordering!");
3533 }
3534 { // 6-bit char6 VST_CODE_BBENTRY strings.
3535 auto Abbv = std::make_shared<BitCodeAbbrev>();
3541 VST_BBENTRY_6_ABBREV)
3542 llvm_unreachable("Unexpected abbrev ordering!");
3543 }
3544
3545 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3546 auto Abbv = std::make_shared<BitCodeAbbrev>();
3551 CONSTANTS_SETTYPE_ABBREV)
3552 llvm_unreachable("Unexpected abbrev ordering!");
3553 }
3554
3555 { // INTEGER abbrev for CONSTANTS_BLOCK.
3556 auto Abbv = std::make_shared<BitCodeAbbrev>();
3560 CONSTANTS_INTEGER_ABBREV)
3561 llvm_unreachable("Unexpected abbrev ordering!");
3562 }
3563
3564 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3565 auto Abbv = std::make_shared<BitCodeAbbrev>();
3567 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3568 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3570 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3571
3573 CONSTANTS_CE_CAST_Abbrev)
3574 llvm_unreachable("Unexpected abbrev ordering!");
3575 }
3576 { // NULL abbrev for CONSTANTS_BLOCK.
3577 auto Abbv = std::make_shared<BitCodeAbbrev>();
3580 CONSTANTS_NULL_Abbrev)
3581 llvm_unreachable("Unexpected abbrev ordering!");
3582 }
3583
3584 // FIXME: This should only use space for first class types!
3585
3586 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3587 auto Abbv = std::make_shared<BitCodeAbbrev>();
3589 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3590 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3592 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3593 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3594 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3595 FUNCTION_INST_LOAD_ABBREV)
3596 llvm_unreachable("Unexpected abbrev ordering!");
3597 }
3598 { // INST_UNOP abbrev for FUNCTION_BLOCK.
3599 auto Abbv = std::make_shared<BitCodeAbbrev>();
3601 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3602 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3603 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3604 FUNCTION_INST_UNOP_ABBREV)
3605 llvm_unreachable("Unexpected abbrev ordering!");
3606 }
3607 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3608 auto Abbv = std::make_shared<BitCodeAbbrev>();
3610 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3611 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3612 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3613 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3614 FUNCTION_INST_UNOP_FLAGS_ABBREV)
3615 llvm_unreachable("Unexpected abbrev ordering!");
3616 }
3617 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3618 auto Abbv = std::make_shared<BitCodeAbbrev>();
3620 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3621 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3622 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3623 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3624 FUNCTION_INST_BINOP_ABBREV)
3625 llvm_unreachable("Unexpected abbrev ordering!");
3626 }
3627 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3628 auto Abbv = std::make_shared<BitCodeAbbrev>();
3630 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3631 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3632 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3633 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3634 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3635 FUNCTION_INST_BINOP_FLAGS_ABBREV)
3636 llvm_unreachable("Unexpected abbrev ordering!");
3637 }
3638 { // INST_CAST abbrev for FUNCTION_BLOCK.
3639 auto Abbv = std::make_shared<BitCodeAbbrev>();
3641 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3642 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3644 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3645 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3646 FUNCTION_INST_CAST_ABBREV)
3647 llvm_unreachable("Unexpected abbrev ordering!");
3648 }
3649
3650 { // INST_RET abbrev for FUNCTION_BLOCK.
3651 auto Abbv = std::make_shared<BitCodeAbbrev>();
3653 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3654 FUNCTION_INST_RET_VOID_ABBREV)
3655 llvm_unreachable("Unexpected abbrev ordering!");
3656 }
3657 { // INST_RET abbrev for FUNCTION_BLOCK.
3658 auto Abbv = std::make_shared<BitCodeAbbrev>();
3660 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3661 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3662 FUNCTION_INST_RET_VAL_ABBREV)
3663 llvm_unreachable("Unexpected abbrev ordering!");
3664 }
3665 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3666 auto Abbv = std::make_shared<BitCodeAbbrev>();
3668 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3669 FUNCTION_INST_UNREACHABLE_ABBREV)
3670 llvm_unreachable("Unexpected abbrev ordering!");
3671 }
3672 {
3673 auto Abbv = std::make_shared<BitCodeAbbrev>();
3676 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3677 Log2_32_Ceil(VE.getTypes().size() + 1)));
3680 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3681 FUNCTION_INST_GEP_ABBREV)
3682 llvm_unreachable("Unexpected abbrev ordering!");
3683 }
3684
3685 Stream.ExitBlock();
3686}
3687
3688/// Write the module path strings, currently only used when generating
3689/// a combined index file.
3690void IndexBitcodeWriter::writeModStrings() {
3692
3693 // TODO: See which abbrev sizes we actually need to emit
3694
3695 // 8-bit fixed-width MST_ENTRY strings.
3696 auto Abbv = std::make_shared<BitCodeAbbrev>();
3701 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3702
3703 // 7-bit fixed width MST_ENTRY strings.
3704 Abbv = std::make_shared<BitCodeAbbrev>();
3709 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3710
3711 // 6-bit char6 MST_ENTRY strings.
3712 Abbv = std::make_shared<BitCodeAbbrev>();
3717 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3718
3719 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3720 Abbv = std::make_shared<BitCodeAbbrev>();
3727 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3728
3730 forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
3731 StringRef Key = MPSE.getKey();
3732 const auto &Hash = MPSE.getValue();
3734 unsigned AbbrevToUse = Abbrev8Bit;
3735 if (Bits == SE_Char6)
3736 AbbrevToUse = Abbrev6Bit;
3737 else if (Bits == SE_Fixed7)
3738 AbbrevToUse = Abbrev7Bit;
3739
3740 auto ModuleId = ModuleIdMap.size();
3741 ModuleIdMap[Key] = ModuleId;
3742 Vals.push_back(ModuleId);
3743 Vals.append(Key.begin(), Key.end());
3744
3745 // Emit the finished record.
3746 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3747
3748 // Emit an optional hash for the module now
3749 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3750 Vals.assign(Hash.begin(), Hash.end());
3751 // Emit the hash record.
3752 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3753 }
3754
3755 Vals.clear();
3756 });
3757 Stream.ExitBlock();
3758}
3759
3760/// Write the function type metadata related records that need to appear before
3761/// a function summary entry (whether per-module or combined).
3762template <typename Fn>
3764 FunctionSummary *FS,
3765 Fn GetValueID) {
3766 if (!FS->type_tests().empty())
3767 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3768
3770
3771 auto WriteVFuncIdVec = [&](uint64_t Ty,
3773 if (VFs.empty())
3774 return;
3775 Record.clear();
3776 for (auto &VF : VFs) {
3777 Record.push_back(VF.GUID);
3778 Record.push_back(VF.Offset);
3779 }
3780 Stream.EmitRecord(Ty, Record);
3781 };
3782
3783 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3784 FS->type_test_assume_vcalls());
3785 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3786 FS->type_checked_load_vcalls());
3787
3788 auto WriteConstVCallVec = [&](uint64_t Ty,
3790 for (auto &VC : VCs) {
3791 Record.clear();
3792 Record.push_back(VC.VFunc.GUID);
3793 Record.push_back(VC.VFunc.Offset);
3794 llvm::append_range(Record, VC.Args);
3795 Stream.EmitRecord(Ty, Record);
3796 }
3797 };
3798
3799 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3800 FS->type_test_assume_const_vcalls());
3801 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3802 FS->type_checked_load_const_vcalls());
3803
3804 auto WriteRange = [&](ConstantRange Range) {
3805 Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
3806 assert(Range.getLower().getNumWords() == 1);
3807 assert(Range.getUpper().getNumWords() == 1);
3808 emitSignedInt64(Record, *Range.getLower().getRawData());
3809 emitSignedInt64(Record, *Range.getUpper().getRawData());
3810 };
3811
3812 if (!FS->paramAccesses().empty()) {
3813 Record.clear();
3814 for (auto &Arg : FS->paramAccesses()) {
3815 size_t UndoSize = Record.size();
3816 Record.push_back(Arg.ParamNo);
3817 WriteRange(Arg.Use);
3818 Record.push_back(Arg.Calls.size());
3819 for (auto &Call : Arg.Calls) {
3820 Record.push_back(Call.ParamNo);
3821 std::optional<unsigned> ValueID = GetValueID(Call.Callee);
3822 if (!ValueID) {
3823 // If ValueID is unknown we can't drop just this call, we must drop
3824 // entire parameter.
3825 Record.resize(UndoSize);
3826 break;
3827 }
3828 Record.push_back(*ValueID);
3829 WriteRange(Call.Offsets);
3830 }
3831 }
3832 if (!Record.empty())
3834 }
3835}
3836
3837/// Collect type IDs from type tests used by function.
3838static void
3840 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
3841 if (!FS->type_tests().empty())
3842 for (auto &TT : FS->type_tests())
3843 ReferencedTypeIds.insert(TT);
3844
3845 auto GetReferencedTypesFromVFuncIdVec =
3847 for (auto &VF : VFs)
3848 ReferencedTypeIds.insert(VF.GUID);
3849 };
3850
3851 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
3852 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
3853
3854 auto GetReferencedTypesFromConstVCallVec =
3856 for (auto &VC : VCs)
3857 ReferencedTypeIds.insert(VC.VFunc.GUID);
3858 };
3859
3860 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
3861 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
3862}
3863
3865 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3867 NameVals.push_back(args.size());
3868 llvm::append_range(NameVals, args);
3869
3870 NameVals.push_back(ByArg.TheKind);
3871 NameVals.push_back(ByArg.Info);
3872 NameVals.push_back(ByArg.Byte);
3873 NameVals.push_back(ByArg.Bit);
3874}
3875
3877 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3878 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
3879 NameVals.push_back(Id);
3880
3881 NameVals.push_back(Wpd.TheKind);
3882 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3883 NameVals.push_back(Wpd.SingleImplName.size());
3884
3885 NameVals.push_back(Wpd.ResByArg.size());
3886 for (auto &A : Wpd.ResByArg)
3887 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3888}
3889
3891 StringTableBuilder &StrtabBuilder,
3892 const std::string &Id,
3893 const TypeIdSummary &Summary) {
3894 NameVals.push_back(StrtabBuilder.add(Id));
3895 NameVals.push_back(Id.size());
3896
3897 NameVals.push_back(Summary.TTRes.TheKind);
3898 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3899 NameVals.push_back(Summary.TTRes.AlignLog2);
3900 NameVals.push_back(Summary.TTRes.SizeM1);
3901 NameVals.push_back(Summary.TTRes.BitMask);
3902 NameVals.push_back(Summary.TTRes.InlineBits);
3903
3904 for (auto &W : Summary.WPDRes)
3905 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3906 W.second);
3907}
3908
3910 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3911 const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
3912 ValueEnumerator &VE) {
3913 NameVals.push_back(StrtabBuilder.add(Id));
3914 NameVals.push_back(Id.size());
3915
3916 for (auto &P : Summary) {
3917 NameVals.push_back(P.AddressPointOffset);
3918 NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
3919 }
3920}
3921
3923 BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
3924 unsigned AllocAbbrev, bool PerModule,
3925 std::function<unsigned(const ValueInfo &VI)> GetValueID,
3926 std::function<unsigned(unsigned)> GetStackIndex) {
3928
3929 for (auto &CI : FS->callsites()) {
3930 Record.clear();
3931 // Per module callsite clones should always have a single entry of
3932 // value 0.
3933 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
3934 Record.push_back(GetValueID(CI.Callee));
3935 if (!PerModule) {
3936 Record.push_back(CI.StackIdIndices.size());
3937 Record.push_back(CI.Clones.size());
3938 }
3939 for (auto Id : CI.StackIdIndices)
3940 Record.push_back(GetStackIndex(Id));
3941 if (!PerModule) {
3942 for (auto V : CI.Clones)
3943 Record.push_back(V);
3944 }
3947 Record, CallsiteAbbrev);
3948 }
3949
3950 for (auto &AI : FS->allocs()) {
3951 Record.clear();
3952 // Per module alloc versions should always have a single entry of
3953 // value 0.
3954 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
3955 if (!PerModule) {
3956 Record.push_back(AI.MIBs.size());
3957 Record.push_back(AI.Versions.size());
3958 }
3959 for (auto &MIB : AI.MIBs) {
3960 Record.push_back((uint8_t)MIB.AllocType);
3961 Record.push_back(MIB.StackIdIndices.size());
3962 for (auto Id : MIB.StackIdIndices)
3963 Record.push_back(GetStackIndex(Id));
3964 }
3965 if (!PerModule) {
3966 for (auto V : AI.Versions)
3967 Record.push_back(V);
3968 }
3969 Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_ALLOC_INFO
3971 Record, AllocAbbrev);
3972 }
3973}
3974
3975// Helper to emit a single function summary record.
3976void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
3978 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3979 unsigned CallsiteAbbrev, unsigned AllocAbbrev, const Function &F) {
3980 NameVals.push_back(ValueID);
3981
3982 FunctionSummary *FS = cast<FunctionSummary>(Summary);
3983
3985 Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
3986 return {VE.getValueID(VI.getValue())};
3987 });
3988
3990 Stream, FS, CallsiteAbbrev, AllocAbbrev,
3991 /*PerModule*/ true,
3992 /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
3993 /*GetStackIndex*/ [&](unsigned I) { return I; });
3994
3995 auto SpecialRefCnts = FS->specialRefCounts();
3996 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3997 NameVals.push_back(FS->instCount());
3998 NameVals.push_back(getEncodedFFlags(FS->fflags()));
3999 NameVals.push_back(FS->refs().size());
4000 NameVals.push_back(SpecialRefCnts.first); // rorefcnt
4001 NameVals.push_back(SpecialRefCnts.second); // worefcnt
4002
4003 for (auto &RI : FS->refs())
4004 NameVals.push_back(VE.getValueID(RI.getValue()));
4005
4006 bool HasProfileData =
4007 F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
4008 for (auto &ECI : FS->calls()) {
4009 NameVals.push_back(getValueId(ECI.first));
4010 if (HasProfileData)
4011 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
4012 else if (WriteRelBFToSummary)
4013 NameVals.push_back(ECI.second.RelBlockFreq);
4014 }
4015
4016 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
4017 unsigned Code =
4018 (HasProfileData ? bitc::FS_PERMODULE_PROFILE
4021
4022 // Emit the finished record.
4023 Stream.EmitRecord(Code, NameVals, FSAbbrev);
4024 NameVals.clear();
4025}
4026
4027// Collect the global value references in the given variable's initializer,
4028// and emit them in a summary record.
4029void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4030 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4031 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
4032 auto VI = Index->getValueInfo(V.getGUID());
4033 if (!VI || VI.getSummaryList().empty()) {
4034 // Only declarations should not have a summary (a declaration might however
4035 // have a summary if the def was in module level asm).
4036 assert(V.isDeclaration());
4037 return;
4038 }
4039 auto *Summary = VI.getSummaryList()[0].get();
4040 NameVals.push_back(VE.getValueID(&V));
4041 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
4042 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4043 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4044
4045 auto VTableFuncs = VS->vTableFuncs();
4046 if (!VTableFuncs.empty())
4047 NameVals.push_back(VS->refs().size());
4048
4049 unsigned SizeBeforeRefs = NameVals.size();
4050 for (auto &RI : VS->refs())
4051 NameVals.push_back(VE.getValueID(RI.getValue()));
4052 // Sort the refs for determinism output, the vector returned by FS->refs() has
4053 // been initialized from a DenseSet.
4054 llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
4055
4056 if (VTableFuncs.empty())
4058 FSModRefsAbbrev);
4059 else {
4060 // VTableFuncs pairs should already be sorted by offset.
4061 for (auto &P : VTableFuncs) {
4062 NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
4063 NameVals.push_back(P.VTableOffset);
4064 }
4065
4067 FSModVTableRefsAbbrev);
4068 }
4069 NameVals.clear();
4070}
4071
4072/// Emit the per-module summary section alongside the rest of
4073/// the module's bitcode.
4074void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4075 // By default we compile with ThinLTO if the module has a summary, but the
4076 // client can request full LTO with a module flag.
4077 bool IsThinLTO = true;
4078 if (auto *MD =
4079 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
4080 IsThinLTO = MD->getZExtValue();
4083 4);
4084
4085 Stream.EmitRecord(
4088
4089 // Write the index flags.
4090 uint64_t Flags = 0;
4091 // Bits 1-3 are set only in the combined index, skip them.
4092 if (Index->enableSplitLTOUnit())
4093 Flags |= 0x8;
4094 if (Index->hasUnifiedLTO())
4095 Flags |= 0x200;
4096
4098
4099 if (Index->begin() == Index->end()) {
4100 Stream.ExitBlock();
4101 return;
4102 }
4103
4104 for (const auto &GVI : valueIds()) {
4106 ArrayRef<uint64_t>{GVI.second, GVI.first});
4107 }
4108
4109 if (!Index->stackIds().empty()) {
4110 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4111 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4112 // numids x stackid
4113 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4114 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4115 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4116 Stream.EmitRecord(bitc::FS_STACK_IDS, Index->stackIds(), StackIdAbbvId);
4117 }
4118
4119 // Abbrev for FS_PERMODULE_PROFILE.
4120 auto Abbv = std::make_shared<BitCodeAbbrev>();
4122 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4123 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags
4124 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4125 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4126 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4127 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4128 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4129 // numrefs x valueid, n x (valueid, hotness)
4132 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4133
4134 // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
4135 Abbv = std::make_shared<BitCodeAbbrev>();
4138 else
4140 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4141 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4142 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4143 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4144 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4145 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4146 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4147 // numrefs x valueid, n x (valueid [, rel_block_freq])
4150 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4151
4152 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4153 Abbv = std::make_shared<BitCodeAbbrev>();
4155 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4156 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4157 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4159 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4160
4161 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4162 Abbv = std::make_shared<BitCodeAbbrev>();
4164 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4165 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4166 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4167 // numrefs x valueid, n x (valueid , offset)
4170 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4171
4172 // Abbrev for FS_ALIAS.
4173 Abbv = std::make_shared<BitCodeAbbrev>();
4174 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4175 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4176 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4177 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4178 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4179
4180 // Abbrev for FS_TYPE_ID_METADATA
4181 Abbv = std::make_shared<BitCodeAbbrev>();
4183 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4184 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4185 // n x (valueid , offset)
4188 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4189
4190 Abbv = std::make_shared<BitCodeAbbrev>();
4192 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4193 // n x stackidindex
4196 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4197
4198 Abbv = std::make_shared<BitCodeAbbrev>();
4200 // n x (alloc type, numstackids, numstackids x stackidindex)
4203 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4204
4206 // Iterate over the list of functions instead of the Index to
4207 // ensure the ordering is stable.
4208 for (const Function &F : M) {
4209 // Summary emission does not support anonymous functions, they have to
4210 // renamed using the anonymous function renaming pass.
4211 if (!F.hasName())
4212 report_fatal_error("Unexpected anonymous function when writing summary");
4213
4214 ValueInfo VI = Index->getValueInfo(F.getGUID());
4215 if (!VI || VI.getSummaryList().empty()) {
4216 // Only declarations should not have a summary (a declaration might
4217 // however have a summary if the def was in module level asm).
4218 assert(F.isDeclaration());
4219 continue;
4220 }
4221 auto *Summary = VI.getSummaryList()[0].get();
4222 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
4223 FSCallsAbbrev, FSCallsProfileAbbrev,
4224 CallsiteAbbrev, AllocAbbrev, F);
4225 }
4226
4227 // Capture references from GlobalVariable initializers, which are outside
4228 // of a function scope.
4229 for (const GlobalVariable &G : M.globals())
4230 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4231 FSModVTableRefsAbbrev);
4232
4233 for (const GlobalAlias &A : M.aliases()) {
4234 auto *Aliasee = A.getAliaseeObject();
4235 // Skip ifunc and nameless functions which don't have an entry in the
4236 // summary.
4237 if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
4238 continue;
4239 auto AliasId = VE.getValueID(&A);
4240 auto AliaseeId = VE.getValueID(Aliasee);
4241 NameVals.push_back(AliasId);
4242 auto *Summary = Index->getGlobalValueSummary(A);
4243 AliasSummary *AS = cast<AliasSummary>(Summary);
4244 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4245 NameVals.push_back(AliaseeId);
4246 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4247 NameVals.clear();
4248 }
4249
4250 for (auto &S : Index->typeIdCompatibleVtableMap()) {
4251 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4252 S.second, VE);
4253 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4254 TypeIdCompatibleVtableAbbrev);
4255 NameVals.clear();
4256 }
4257
4258 if (Index->getBlockCount())
4260 ArrayRef<uint64_t>{Index->getBlockCount()});
4261
4262 Stream.ExitBlock();
4263}
4264
4265/// Emit the combined summary section into the combined index file.
4266void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4268 Stream.EmitRecord(
4271
4272 // Write the index flags.
4274
4275 for (const auto &GVI : valueIds()) {
4277 ArrayRef<uint64_t>{GVI.second, GVI.first});
4278 }
4279
4280 if (!StackIdIndices.empty()) {
4281 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4282 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4283 // numids x stackid
4284 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4285 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4286 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4287 // Write the stack ids used by this index, which will be a subset of those in
4288 // the full index in the case of distributed indexes.
4289 std::vector<uint64_t> StackIds;
4290 for (auto &I : StackIdIndices)
4291 StackIds.push_back(Index.getStackIdAtIndex(I));
4292 Stream.EmitRecord(bitc::FS_STACK_IDS, StackIds, StackIdAbbvId);
4293 }
4294
4295 // Abbrev for FS_COMBINED.
4296 auto Abbv = std::make_shared<BitCodeAbbrev>();
4298 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4299 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4300 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4301 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4302 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4303 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
4304 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4305 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4306 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4307 // numrefs x valueid, n x (valueid)
4310 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4311
4312 // Abbrev for FS_COMBINED_PROFILE.
4313 Abbv = std::make_shared<BitCodeAbbrev>();
4315 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4316 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4317 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4318 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4319 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4320 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
4321 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4322 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4323 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4324 // numrefs x valueid, n x (valueid, hotness)
4327 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4328
4329 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
4330 Abbv = std::make_shared<BitCodeAbbrev>();
4332 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4333 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4334 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4335 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4337 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4338
4339 // Abbrev for FS_COMBINED_ALIAS.
4340 Abbv = std::make_shared<BitCodeAbbrev>();
4342 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4343 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4344 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4345 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4346 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4347
4348 Abbv = std::make_shared<BitCodeAbbrev>();