LLVM 20.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"
37#include "llvm/IR/Constants.h"
39#include "llvm/IR/DebugLoc.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/GlobalAlias.h"
43#include "llvm/IR/GlobalIFunc.h"
45#include "llvm/IR/GlobalValue.h"
47#include "llvm/IR/InlineAsm.h"
48#include "llvm/IR/InstrTypes.h"
49#include "llvm/IR/Instruction.h"
51#include "llvm/IR/LLVMContext.h"
52#include "llvm/IR/Metadata.h"
53#include "llvm/IR/Module.h"
55#include "llvm/IR/Operator.h"
56#include "llvm/IR/Type.h"
58#include "llvm/IR/Value.h"
67#include "llvm/Support/Endian.h"
68#include "llvm/Support/Error.h"
71#include "llvm/Support/SHA1.h"
74#include <algorithm>
75#include <cassert>
76#include <cstddef>
77#include <cstdint>
78#include <iterator>
79#include <map>
80#include <memory>
81#include <optional>
82#include <string>
83#include <utility>
84#include <vector>
85
86using namespace llvm;
87using namespace llvm::memprof;
88
90 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
91 cl::desc("Number of metadatas above which we emit an index "
92 "to enable lazy-loading"));
94 "bitcode-flush-threshold", cl::Hidden, cl::init(512),
95 cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
96
98 "write-relbf-to-summary", cl::Hidden, cl::init(false),
99 cl::desc("Write relative block frequency to function summary "));
100
101namespace llvm {
103}
104
107
108namespace {
109
110/// These are manifest constants used by the bitcode writer. They do not need to
111/// be kept in sync with the reader, but need to be consistent within this file.
112enum {
113 // VALUE_SYMTAB_BLOCK abbrev id's.
114 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
115 VST_ENTRY_7_ABBREV,
116 VST_ENTRY_6_ABBREV,
117 VST_BBENTRY_6_ABBREV,
118
119 // CONSTANTS_BLOCK abbrev id's.
120 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
121 CONSTANTS_INTEGER_ABBREV,
122 CONSTANTS_CE_CAST_Abbrev,
123 CONSTANTS_NULL_Abbrev,
124
125 // FUNCTION_BLOCK abbrev id's.
126 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
127 FUNCTION_INST_UNOP_ABBREV,
128 FUNCTION_INST_UNOP_FLAGS_ABBREV,
129 FUNCTION_INST_BINOP_ABBREV,
130 FUNCTION_INST_BINOP_FLAGS_ABBREV,
131 FUNCTION_INST_CAST_ABBREV,
132 FUNCTION_INST_CAST_FLAGS_ABBREV,
133 FUNCTION_INST_RET_VOID_ABBREV,
134 FUNCTION_INST_RET_VAL_ABBREV,
135 FUNCTION_INST_UNREACHABLE_ABBREV,
136 FUNCTION_INST_GEP_ABBREV,
137 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
138};
139
140/// Abstract class to manage the bitcode writing, subclassed for each bitcode
141/// file type.
142class BitcodeWriterBase {
143protected:
144 /// The stream created and owned by the client.
145 BitstreamWriter &Stream;
146
147 StringTableBuilder &StrtabBuilder;
148
149public:
150 /// Constructs a BitcodeWriterBase object that writes to the provided
151 /// \p Stream.
152 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
153 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
154
155protected:
156 void writeModuleVersion();
157};
158
159void BitcodeWriterBase::writeModuleVersion() {
160 // VERSION: [version#]
161 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
162}
163
164/// Base class to manage the module bitcode writing, currently subclassed for
165/// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
166class ModuleBitcodeWriterBase : public BitcodeWriterBase {
167protected:
168 /// The Module to write to bitcode.
169 const Module &M;
170
171 /// Enumerates ids for all values in the module.
173
174 /// Optional per-module index to write for ThinLTO.
176
177 /// Map that holds the correspondence between GUIDs in the summary index,
178 /// that came from indirect call profiles, and a value id generated by this
179 /// class to use in the VST and summary block records.
180 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
181
182 /// Tracks the last value id recorded in the GUIDToValueMap.
183 unsigned GlobalValueId;
184
185 /// Saves the offset of the VSTOffset record that must eventually be
186 /// backpatched with the offset of the actual VST.
187 uint64_t VSTOffsetPlaceholder = 0;
188
189public:
190 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
191 /// writing to the provided \p Buffer.
192 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
193 BitstreamWriter &Stream,
194 bool ShouldPreserveUseListOrder,
195 const ModuleSummaryIndex *Index)
196 : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
197 VE(M, ShouldPreserveUseListOrder), Index(Index) {
198 // Assign ValueIds to any callee values in the index that came from
199 // indirect call profiles and were recorded as a GUID not a Value*
200 // (which would have been assigned an ID by the ValueEnumerator).
201 // The starting ValueId is just after the number of values in the
202 // ValueEnumerator, so that they can be emitted in the VST.
203 GlobalValueId = VE.getValues().size();
204 if (!Index)
205 return;
206 for (const auto &GUIDSummaryLists : *Index)
207 // Examine all summaries for this GUID.
208 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
209 if (auto FS = dyn_cast<FunctionSummary>(Summary.get())) {
210 // For each call in the function summary, see if the call
211 // is to a GUID (which means it is for an indirect call,
212 // otherwise we would have a Value for it). If so, synthesize
213 // a value id.
214 for (auto &CallEdge : FS->calls())
215 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
216 assignValueId(CallEdge.first.getGUID());
217
218 // For each referenced variables in the function summary, see if the
219 // variable is represented by a GUID (as opposed to a symbol to
220 // declarations or definitions in the module). If so, synthesize a
221 // value id.
222 for (auto &RefEdge : FS->refs())
223 if (!RefEdge.haveGVs() || !RefEdge.getValue())
224 assignValueId(RefEdge.getGUID());
225 }
226 }
227
228protected:
229 void writePerModuleGlobalValueSummary();
230
231private:
232 void writePerModuleFunctionSummaryRecord(
234 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
235 unsigned CallsiteAbbrev, unsigned AllocAbbrev, unsigned ContextIdAbbvId,
237 CallStackId &CallStackCount);
238 void writeModuleLevelReferences(const GlobalVariable &V,
240 unsigned FSModRefsAbbrev,
241 unsigned FSModVTableRefsAbbrev);
242
243 void assignValueId(GlobalValue::GUID ValGUID) {
244 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
245 }
246
247 unsigned getValueId(GlobalValue::GUID ValGUID) {
248 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
249 // Expect that any GUID value had a value Id assigned by an
250 // earlier call to assignValueId.
251 assert(VMI != GUIDToValueIdMap.end() &&
252 "GUID does not have assigned value Id");
253 return VMI->second;
254 }
255
256 // Helper to get the valueId for the type of value recorded in VI.
257 unsigned getValueId(ValueInfo VI) {
258 if (!VI.haveGVs() || !VI.getValue())
259 return getValueId(VI.getGUID());
260 return VE.getValueID(VI.getValue());
261 }
262
263 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
264};
265
266/// Class to manage the bitcode writing for a module.
267class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
268 /// True if a module hash record should be written.
269 bool GenerateHash;
270
271 /// If non-null, when GenerateHash is true, the resulting hash is written
272 /// into ModHash.
273 ModuleHash *ModHash;
274
275 SHA1 Hasher;
276
277 /// The start bit of the identification block.
278 uint64_t BitcodeStartBit;
279
280public:
281 /// Constructs a ModuleBitcodeWriter object for the given Module,
282 /// writing to the provided \p Buffer.
283 ModuleBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
284 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
285 const ModuleSummaryIndex *Index, bool GenerateHash,
286 ModuleHash *ModHash = nullptr)
287 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
288 ShouldPreserveUseListOrder, Index),
289 GenerateHash(GenerateHash), ModHash(ModHash),
290 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
291
292 /// Emit the current module to the bitstream.
293 void write();
294
295private:
296 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
297
298 size_t addToStrtab(StringRef Str);
299
300 void writeAttributeGroupTable();
301 void writeAttributeTable();
302 void writeTypeTable();
303 void writeComdats();
304 void writeValueSymbolTableForwardDecl();
305 void writeModuleInfo();
306 void writeValueAsMetadata(const ValueAsMetadata *MD,
309 unsigned Abbrev);
310 unsigned createDILocationAbbrev();
312 unsigned &Abbrev);
313 unsigned createGenericDINodeAbbrev();
315 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
317 unsigned Abbrev);
320 unsigned Abbrev);
321 void writeDIEnumerator(const DIEnumerator *N,
322 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
324 unsigned Abbrev);
325 void writeDIStringType(const DIStringType *N,
326 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
328 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
330 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
333 unsigned Abbrev);
335 unsigned Abbrev);
337 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
338 void writeDISubprogram(const DISubprogram *N,
339 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
341 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
344 unsigned Abbrev);
346 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
348 unsigned Abbrev);
350 unsigned Abbrev);
352 unsigned Abbrev);
355 unsigned Abbrev);
357 unsigned Abbrev);
360 unsigned Abbrev);
363 unsigned Abbrev);
366 unsigned Abbrev);
368 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
369 void writeDILabel(const DILabel *N,
370 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
371 void writeDIExpression(const DIExpression *N,
372 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
375 unsigned Abbrev);
377 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
380 unsigned Abbrev);
381 unsigned createNamedMetadataAbbrev();
382 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
383 unsigned createMetadataStringsAbbrev();
384 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
386 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
388 std::vector<unsigned> *MDAbbrevs = nullptr,
389 std::vector<uint64_t> *IndexPos = nullptr);
390 void writeModuleMetadata();
391 void writeFunctionMetadata(const Function &F);
392 void writeFunctionMetadataAttachment(const Function &F);
393 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
394 const GlobalObject &GO);
395 void writeModuleMetadataKinds();
396 void writeOperandBundleTags();
397 void writeSyncScopeNames();
398 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
399 void writeModuleConstants();
400 bool pushValueAndType(const Value *V, unsigned InstID,
402 bool pushValueOrMetadata(const Value *V, unsigned InstID,
404 void writeOperandBundles(const CallBase &CB, unsigned InstID);
405 void pushValue(const Value *V, unsigned InstID,
407 void pushValueSigned(const Value *V, unsigned InstID,
409 void writeInstruction(const Instruction &I, unsigned InstID,
411 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
412 void writeGlobalValueSymbolTable(
413 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
414 void writeUseList(UseListOrder &&Order);
415 void writeUseListBlock(const Function *F);
416 void
417 writeFunction(const Function &F,
418 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
419 void writeBlockInfo();
420 void writeModuleHash(StringRef View);
421
422 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
423 return unsigned(SSID);
424 }
425
426 unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
427};
428
429/// Class to manage the bitcode writing for a combined index.
430class IndexBitcodeWriter : public BitcodeWriterBase {
431 /// The combined index to write to bitcode.
433
434 /// When writing combined summaries, provides the set of global value
435 /// summaries for which the value (function, function alias, etc) should be
436 /// imported as a declaration.
437 const GVSummaryPtrSet *DecSummaries = nullptr;
438
439 /// When writing a subset of the index for distributed backends, client
440 /// provides a map of modules to the corresponding GUIDs/summaries to write.
441 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex;
442
443 /// Map that holds the correspondence between the GUID used in the combined
444 /// index and a value id generated by this class to use in references.
445 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
446
447 // The stack ids used by this index, which will be a subset of those in
448 // the full index in the case of distributed indexes.
449 std::vector<uint64_t> StackIds;
450
451 // Keep a map of the stack id indices used by records being written for this
452 // index to the index of the corresponding stack id in the above StackIds
453 // vector. Ensures we write each referenced stack id once.
454 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
455
456 /// Tracks the last value id recorded in the GUIDToValueMap.
457 unsigned GlobalValueId = 0;
458
459 /// Tracks the assignment of module paths in the module path string table to
460 /// an id assigned for use in summary references to the module path.
462
463public:
464 /// Constructs a IndexBitcodeWriter object for the given combined index,
465 /// writing to the provided \p Buffer. When writing a subset of the index
466 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
467 /// If provided, \p DecSummaries specifies the set of summaries for which
468 /// the corresponding functions or aliased functions should be imported as a
469 /// declaration (but not definition) for each module.
470 IndexBitcodeWriter(
471 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
472 const ModuleSummaryIndex &Index,
473 const GVSummaryPtrSet *DecSummaries = nullptr,
474 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex = nullptr)
475 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
476 DecSummaries(DecSummaries),
477 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
478
479 // See if the StackIdIndex was already added to the StackId map and
480 // vector. If not, record it.
481 auto RecordStackIdReference = [&](unsigned StackIdIndex) {
482 // If the StackIdIndex is not yet in the map, the below insert ensures
483 // that it will point to the new StackIds vector entry we push to just
484 // below.
485 auto Inserted =
486 StackIdIndicesToIndex.insert({StackIdIndex, StackIds.size()});
487 if (Inserted.second)
488 StackIds.push_back(Index.getStackIdAtIndex(StackIdIndex));
489 };
490
491 // Assign unique value ids to all summaries to be written, for use
492 // in writing out the call graph edges. Save the mapping from GUID
493 // to the new global value id to use when writing those edges, which
494 // are currently saved in the index in terms of GUID.
495 forEachSummary([&](GVInfo I, bool IsAliasee) {
496 GUIDToValueIdMap[I.first] = ++GlobalValueId;
497 if (IsAliasee)
498 return;
499 auto *FS = dyn_cast<FunctionSummary>(I.second);
500 if (!FS)
501 return;
502 // Record all stack id indices actually used in the summary entries being
503 // written, so that we can compact them in the case of distributed ThinLTO
504 // indexes.
505 for (auto &CI : FS->callsites()) {
506 // If the stack id list is empty, this callsite info was synthesized for
507 // a missing tail call frame. Ensure that the callee's GUID gets a value
508 // id. Normally we only generate these for defined summaries, which in
509 // the case of distributed ThinLTO is only the functions already defined
510 // in the module or that we want to import. We don't bother to include
511 // all the callee symbols as they aren't normally needed in the backend.
512 // However, for the synthesized callsite infos we do need the callee
513 // GUID in the backend so that we can correlate the identified callee
514 // with this callsite info (which for non-tail calls is done by the
515 // ordering of the callsite infos and verified via stack ids).
516 if (CI.StackIdIndices.empty()) {
517 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
518 continue;
519 }
520 for (auto Idx : CI.StackIdIndices)
521 RecordStackIdReference(Idx);
522 }
523 for (auto &AI : FS->allocs())
524 for (auto &MIB : AI.MIBs)
525 for (auto Idx : MIB.StackIdIndices)
526 RecordStackIdReference(Idx);
527 });
528 }
529
530 /// The below iterator returns the GUID and associated summary.
531 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
532
533 /// Calls the callback for each value GUID and summary to be written to
534 /// bitcode. This hides the details of whether they are being pulled from the
535 /// entire index or just those in a provided ModuleToSummariesForIndex map.
536 template<typename Functor>
537 void forEachSummary(Functor Callback) {
538 if (ModuleToSummariesForIndex) {
539 for (auto &M : *ModuleToSummariesForIndex)
540 for (auto &Summary : M.second) {
541 Callback(Summary, false);
542 // Ensure aliasee is handled, e.g. for assigning a valueId,
543 // even if we are not importing the aliasee directly (the
544 // imported alias will contain a copy of aliasee).
545 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
546 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
547 }
548 } else {
549 for (auto &Summaries : Index)
550 for (auto &Summary : Summaries.second.SummaryList)
551 Callback({Summaries.first, Summary.get()}, false);
552 }
553 }
554
555 /// Calls the callback for each entry in the modulePaths StringMap that
556 /// should be written to the module path string table. This hides the details
557 /// of whether they are being pulled from the entire index or just those in a
558 /// provided ModuleToSummariesForIndex map.
559 template <typename Functor> void forEachModule(Functor Callback) {
560 if (ModuleToSummariesForIndex) {
561 for (const auto &M : *ModuleToSummariesForIndex) {
562 const auto &MPI = Index.modulePaths().find(M.first);
563 if (MPI == Index.modulePaths().end()) {
564 // This should only happen if the bitcode file was empty, in which
565 // case we shouldn't be importing (the ModuleToSummariesForIndex
566 // would only include the module we are writing and index for).
567 assert(ModuleToSummariesForIndex->size() == 1);
568 continue;
569 }
570 Callback(*MPI);
571 }
572 } else {
573 // Since StringMap iteration order isn't guaranteed, order by path string
574 // first.
575 // FIXME: Make this a vector of StringMapEntry instead to avoid the later
576 // map lookup.
577 std::vector<StringRef> ModulePaths;
578 for (auto &[ModPath, _] : Index.modulePaths())
579 ModulePaths.push_back(ModPath);
580 llvm::sort(ModulePaths.begin(), ModulePaths.end());
581 for (auto &ModPath : ModulePaths)
582 Callback(*Index.modulePaths().find(ModPath));
583 }
584 }
585
586 /// Main entry point for writing a combined index to bitcode.
587 void write();
588
589private:
590 void writeModStrings();
591 void writeCombinedGlobalValueSummary();
592
593 std::optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
594 auto VMI = GUIDToValueIdMap.find(ValGUID);
595 if (VMI == GUIDToValueIdMap.end())
596 return std::nullopt;
597 return VMI->second;
598 }
599
600 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
601};
602
603} // end anonymous namespace
604
605static unsigned getEncodedCastOpcode(unsigned Opcode) {
606 switch (Opcode) {
607 default: llvm_unreachable("Unknown cast instruction!");
608 case Instruction::Trunc : return bitc::CAST_TRUNC;
609 case Instruction::ZExt : return bitc::CAST_ZEXT;
610 case Instruction::SExt : return bitc::CAST_SEXT;
611 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
612 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
613 case Instruction::UIToFP : return bitc::CAST_UITOFP;
614 case Instruction::SIToFP : return bitc::CAST_SITOFP;
615 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
616 case Instruction::FPExt : return bitc::CAST_FPEXT;
617 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
618 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
619 case Instruction::BitCast : return bitc::CAST_BITCAST;
620 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
621 }
622}
623
624static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
625 switch (Opcode) {
626 default: llvm_unreachable("Unknown binary instruction!");
627 case Instruction::FNeg: return bitc::UNOP_FNEG;
628 }
629}
630
631static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
632 switch (Opcode) {
633 default: llvm_unreachable("Unknown binary instruction!");
634 case Instruction::Add:
635 case Instruction::FAdd: return bitc::BINOP_ADD;
636 case Instruction::Sub:
637 case Instruction::FSub: return bitc::BINOP_SUB;
638 case Instruction::Mul:
639 case Instruction::FMul: return bitc::BINOP_MUL;
640 case Instruction::UDiv: return bitc::BINOP_UDIV;
641 case Instruction::FDiv:
642 case Instruction::SDiv: return bitc::BINOP_SDIV;
643 case Instruction::URem: return bitc::BINOP_UREM;
644 case Instruction::FRem:
645 case Instruction::SRem: return bitc::BINOP_SREM;
646 case Instruction::Shl: return bitc::BINOP_SHL;
647 case Instruction::LShr: return bitc::BINOP_LSHR;
648 case Instruction::AShr: return bitc::BINOP_ASHR;
649 case Instruction::And: return bitc::BINOP_AND;
650 case Instruction::Or: return bitc::BINOP_OR;
651 case Instruction::Xor: return bitc::BINOP_XOR;
652 }
653}
654
656 switch (Op) {
657 default: llvm_unreachable("Unknown RMW operation!");
663 case AtomicRMWInst::Or: return bitc::RMW_OR;
674 return bitc::RMW_UINC_WRAP;
676 return bitc::RMW_UDEC_WRAP;
678 return bitc::RMW_USUB_COND;
680 return bitc::RMW_USUB_SAT;
681 }
682}
683
684static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
685 switch (Ordering) {
686 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
687 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
688 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
689 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
690 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
691 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
692 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
693 }
694 llvm_unreachable("Invalid ordering");
695}
696
697static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
698 StringRef Str, unsigned AbbrevToUse) {
700
701 // Code: [strchar x N]
702 for (char C : Str) {
703 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
704 AbbrevToUse = 0;
705 Vals.push_back(C);
706 }
707
708 // Emit the finished record.
709 Stream.EmitRecord(Code, Vals, AbbrevToUse);
710}
711
713 switch (Kind) {
714 case Attribute::Alignment:
716 case Attribute::AllocAlign:
718 case Attribute::AllocSize:
720 case Attribute::AlwaysInline:
722 case Attribute::Builtin:
724 case Attribute::ByVal:
726 case Attribute::Convergent:
728 case Attribute::InAlloca:
730 case Attribute::Cold:
732 case Attribute::DisableSanitizerInstrumentation:
734 case Attribute::FnRetThunkExtern:
736 case Attribute::Hot:
737 return bitc::ATTR_KIND_HOT;
738 case Attribute::ElementType:
740 case Attribute::HybridPatchable:
742 case Attribute::InlineHint:
744 case Attribute::InReg:
746 case Attribute::JumpTable:
748 case Attribute::MinSize:
750 case Attribute::AllocatedPointer:
752 case Attribute::AllocKind:
754 case Attribute::Memory:
756 case Attribute::NoFPClass:
758 case Attribute::Naked:
760 case Attribute::Nest:
762 case Attribute::NoAlias:
764 case Attribute::NoBuiltin:
766 case Attribute::NoCallback:
768 case Attribute::NoCapture:
770 case Attribute::NoDivergenceSource:
772 case Attribute::NoDuplicate:
774 case Attribute::NoFree:
776 case Attribute::NoImplicitFloat:
778 case Attribute::NoInline:
780 case Attribute::NoRecurse:
782 case Attribute::NoMerge:
784 case Attribute::NonLazyBind:
786 case Attribute::NonNull:
788 case Attribute::Dereferenceable:
790 case Attribute::DereferenceableOrNull:
792 case Attribute::NoRedZone:
794 case Attribute::NoReturn:
796 case Attribute::NoSync:
798 case Attribute::NoCfCheck:
800 case Attribute::NoProfile:
802 case Attribute::SkipProfile:
804 case Attribute::NoUnwind:
806 case Attribute::NoSanitizeBounds:
808 case Attribute::NoSanitizeCoverage:
810 case Attribute::NullPointerIsValid:
812 case Attribute::OptimizeForDebugging:
814 case Attribute::OptForFuzzing:
816 case Attribute::OptimizeForSize:
818 case Attribute::OptimizeNone:
820 case Attribute::ReadNone:
822 case Attribute::ReadOnly:
824 case Attribute::Returned:
826 case Attribute::ReturnsTwice:
828 case Attribute::SExt:
830 case Attribute::Speculatable:
832 case Attribute::StackAlignment:
834 case Attribute::StackProtect:
836 case Attribute::StackProtectReq:
838 case Attribute::StackProtectStrong:
840 case Attribute::SafeStack:
842 case Attribute::ShadowCallStack:
844 case Attribute::StrictFP:
846 case Attribute::StructRet:
848 case Attribute::SanitizeAddress:
850 case Attribute::SanitizeHWAddress:
852 case Attribute::SanitizeThread:
854 case Attribute::SanitizeType:
856 case Attribute::SanitizeMemory:
858 case Attribute::SanitizeNumericalStability:
860 case Attribute::SanitizeRealtime:
862 case Attribute::SanitizeRealtimeBlocking:
864 case Attribute::SpeculativeLoadHardening:
866 case Attribute::SwiftError:
868 case Attribute::SwiftSelf:
870 case Attribute::SwiftAsync:
872 case Attribute::UWTable:
874 case Attribute::VScaleRange:
876 case Attribute::WillReturn:
878 case Attribute::WriteOnly:
880 case Attribute::ZExt:
882 case Attribute::ImmArg:
884 case Attribute::SanitizeMemTag:
886 case Attribute::Preallocated:
888 case Attribute::NoUndef:
890 case Attribute::ByRef:
892 case Attribute::MustProgress:
894 case Attribute::PresplitCoroutine:
896 case Attribute::Writable:
898 case Attribute::CoroDestroyOnlyWhenComplete:
900 case Attribute::CoroElideSafe:
902 case Attribute::DeadOnUnwind:
904 case Attribute::Range:
906 case Attribute::Initializes:
908 case Attribute::NoExt:
911 llvm_unreachable("Can not encode end-attribute kinds marker.");
912 case Attribute::None:
913 llvm_unreachable("Can not encode none-attribute.");
916 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
917 }
918
919 llvm_unreachable("Trying to encode unknown attribute");
920}
921
923 if ((int64_t)V >= 0)
924 Vals.push_back(V << 1);
925 else
926 Vals.push_back((-V << 1) | 1);
927}
928
929static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {
930 // We have an arbitrary precision integer value to write whose
931 // bit width is > 64. However, in canonical unsigned integer
932 // format it is likely that the high bits are going to be zero.
933 // So, we only write the number of active words.
934 unsigned NumWords = A.getActiveWords();
935 const uint64_t *RawData = A.getRawData();
936 for (unsigned i = 0; i < NumWords; i++)
937 emitSignedInt64(Vals, RawData[i]);
938}
939
941 const ConstantRange &CR, bool EmitBitWidth) {
942 unsigned BitWidth = CR.getBitWidth();
943 if (EmitBitWidth)
944 Record.push_back(BitWidth);
945 if (BitWidth > 64) {
946 Record.push_back(CR.getLower().getActiveWords() |
947 (uint64_t(CR.getUpper().getActiveWords()) << 32));
950 } else {
953 }
954}
955
956void ModuleBitcodeWriter::writeAttributeGroupTable() {
957 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
959 if (AttrGrps.empty()) return;
960
962
964 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
965 unsigned AttrListIndex = Pair.first;
966 AttributeSet AS = Pair.second;
967 Record.push_back(VE.getAttributeGroupID(Pair));
968 Record.push_back(AttrListIndex);
969
970 for (Attribute Attr : AS) {
971 if (Attr.isEnumAttribute()) {
972 Record.push_back(0);
973 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
974 } else if (Attr.isIntAttribute()) {
975 Record.push_back(1);
976 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
977 Record.push_back(Attr.getValueAsInt());
978 } else if (Attr.isStringAttribute()) {
979 StringRef Kind = Attr.getKindAsString();
980 StringRef Val = Attr.getValueAsString();
981
982 Record.push_back(Val.empty() ? 3 : 4);
983 Record.append(Kind.begin(), Kind.end());
984 Record.push_back(0);
985 if (!Val.empty()) {
986 Record.append(Val.begin(), Val.end());
987 Record.push_back(0);
988 }
989 } else if (Attr.isTypeAttribute()) {
990 Type *Ty = Attr.getValueAsType();
991 Record.push_back(Ty ? 6 : 5);
992 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
993 if (Ty)
994 Record.push_back(VE.getTypeID(Attr.getValueAsType()));
995 } else if (Attr.isConstantRangeAttribute()) {
996 Record.push_back(7);
997 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
998 emitConstantRange(Record, Attr.getValueAsConstantRange(),
999 /*EmitBitWidth=*/true);
1000 } else {
1001 assert(Attr.isConstantRangeListAttribute());
1002 Record.push_back(8);
1003 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1004 ArrayRef<ConstantRange> Val = Attr.getValueAsConstantRangeList();
1005 Record.push_back(Val.size());
1006 Record.push_back(Val[0].getBitWidth());
1007 for (auto &CR : Val)
1008 emitConstantRange(Record, CR, /*EmitBitWidth=*/false);
1009 }
1010 }
1011
1013 Record.clear();
1014 }
1015
1016 Stream.ExitBlock();
1017}
1018
1019void ModuleBitcodeWriter::writeAttributeTable() {
1020 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
1021 if (Attrs.empty()) return;
1022
1024
1026 for (const AttributeList &AL : Attrs) {
1027 for (unsigned i : AL.indexes()) {
1028 AttributeSet AS = AL.getAttributes(i);
1029 if (AS.hasAttributes())
1030 Record.push_back(VE.getAttributeGroupID({i, AS}));
1031 }
1032
1034 Record.clear();
1035 }
1036
1037 Stream.ExitBlock();
1038}
1039
1040/// WriteTypeTable - Write out the type table for a module.
1041void ModuleBitcodeWriter::writeTypeTable() {
1042 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
1043
1044 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
1046
1048
1049 // Abbrev for TYPE_CODE_OPAQUE_POINTER.
1050 auto Abbv = std::make_shared<BitCodeAbbrev>();
1052 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
1053 unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1054
1055 // Abbrev for TYPE_CODE_FUNCTION.
1056 Abbv = std::make_shared<BitCodeAbbrev>();
1058 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
1060 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1061 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1062
1063 // Abbrev for TYPE_CODE_STRUCT_ANON.
1064 Abbv = std::make_shared<BitCodeAbbrev>();
1066 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1068 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1069 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1070
1071 // Abbrev for TYPE_CODE_STRUCT_NAME.
1072 Abbv = std::make_shared<BitCodeAbbrev>();
1076 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1077
1078 // Abbrev for TYPE_CODE_STRUCT_NAMED.
1079 Abbv = std::make_shared<BitCodeAbbrev>();
1081 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1083 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1084 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1085
1086 // Abbrev for TYPE_CODE_ARRAY.
1087 Abbv = std::make_shared<BitCodeAbbrev>();
1089 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
1090 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1091 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1092
1093 // Emit an entry count so the reader can reserve space.
1094 TypeVals.push_back(TypeList.size());
1095 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
1096 TypeVals.clear();
1097
1098 // Loop over all of the types, emitting each in turn.
1099 for (Type *T : TypeList) {
1100 int AbbrevToUse = 0;
1101 unsigned Code = 0;
1102
1103 switch (T->getTypeID()) {
1113 case Type::MetadataTyID:
1115 break;
1118 case Type::IntegerTyID:
1119 // INTEGER: [width]
1121 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
1122 break;
1123 case Type::PointerTyID: {
1124 PointerType *PTy = cast<PointerType>(T);
1125 unsigned AddressSpace = PTy->getAddressSpace();
1126 // OPAQUE_POINTER: [address space]
1128 TypeVals.push_back(AddressSpace);
1129 if (AddressSpace == 0)
1130 AbbrevToUse = OpaquePtrAbbrev;
1131 break;
1132 }
1133 case Type::FunctionTyID: {
1134 FunctionType *FT = cast<FunctionType>(T);
1135 // FUNCTION: [isvararg, retty, paramty x N]
1137 TypeVals.push_back(FT->isVarArg());
1138 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
1139 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1140 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
1141 AbbrevToUse = FunctionAbbrev;
1142 break;
1143 }
1144 case Type::StructTyID: {
1145 StructType *ST = cast<StructType>(T);
1146 // STRUCT: [ispacked, eltty x N]
1147 TypeVals.push_back(ST->isPacked());
1148 // Output all of the element types.
1149 for (Type *ET : ST->elements())
1150 TypeVals.push_back(VE.getTypeID(ET));
1151
1152 if (ST->isLiteral()) {
1154 AbbrevToUse = StructAnonAbbrev;
1155 } else {
1156 if (ST->isOpaque()) {
1158 } else {
1160 AbbrevToUse = StructNamedAbbrev;
1161 }
1162
1163 // Emit the name if it is present.
1164 if (!ST->getName().empty())
1166 StructNameAbbrev);
1167 }
1168 break;
1169 }
1170 case Type::ArrayTyID: {
1171 ArrayType *AT = cast<ArrayType>(T);
1172 // ARRAY: [numelts, eltty]
1174 TypeVals.push_back(AT->getNumElements());
1175 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1176 AbbrevToUse = ArrayAbbrev;
1177 break;
1178 }
1181 VectorType *VT = cast<VectorType>(T);
1182 // VECTOR [numelts, eltty] or
1183 // [numelts, eltty, scalable]
1185 TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1186 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1187 if (isa<ScalableVectorType>(VT))
1188 TypeVals.push_back(true);
1189 break;
1190 }
1191 case Type::TargetExtTyID: {
1192 TargetExtType *TET = cast<TargetExtType>(T);
1195 StructNameAbbrev);
1196 TypeVals.push_back(TET->getNumTypeParameters());
1197 for (Type *InnerTy : TET->type_params())
1198 TypeVals.push_back(VE.getTypeID(InnerTy));
1199 for (unsigned IntParam : TET->int_params())
1200 TypeVals.push_back(IntParam);
1201 break;
1202 }
1204 llvm_unreachable("Typed pointers cannot be added to IR modules");
1205 }
1206
1207 // Emit the finished record.
1208 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1209 TypeVals.clear();
1210 }
1211
1212 Stream.ExitBlock();
1213}
1214
1215static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
1216 switch (Linkage) {
1218 return 0;
1220 return 16;
1222 return 2;
1224 return 3;
1226 return 18;
1228 return 7;
1230 return 8;
1232 return 9;
1234 return 17;
1236 return 19;
1238 return 12;
1239 }
1240 llvm_unreachable("Invalid linkage");
1241}
1242
1243static unsigned getEncodedLinkage(const GlobalValue &GV) {
1244 return getEncodedLinkage(GV.getLinkage());
1245}
1246
1248 uint64_t RawFlags = 0;
1249 RawFlags |= Flags.ReadNone;
1250 RawFlags |= (Flags.ReadOnly << 1);
1251 RawFlags |= (Flags.NoRecurse << 2);
1252 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1253 RawFlags |= (Flags.NoInline << 4);
1254 RawFlags |= (Flags.AlwaysInline << 5);
1255 RawFlags |= (Flags.NoUnwind << 6);
1256 RawFlags |= (Flags.MayThrow << 7);
1257 RawFlags |= (Flags.HasUnknownCall << 8);
1258 RawFlags |= (Flags.MustBeUnreachable << 9);
1259 return RawFlags;
1260}
1261
1262// Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1263// in BitcodeReader.cpp.
1265 bool ImportAsDecl = false) {
1266 uint64_t RawFlags = 0;
1267
1268 RawFlags |= Flags.NotEligibleToImport; // bool
1269 RawFlags |= (Flags.Live << 1);
1270 RawFlags |= (Flags.DSOLocal << 2);
1271 RawFlags |= (Flags.CanAutoHide << 3);
1272
1273 // Linkage don't need to be remapped at that time for the summary. Any future
1274 // change to the getEncodedLinkage() function will need to be taken into
1275 // account here as well.
1276 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1277
1278 RawFlags |= (Flags.Visibility << 8); // 2 bits
1279
1280 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1281 RawFlags |= (ImportType << 10); // 1 bit
1282
1283 return RawFlags;
1284}
1285
1287 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1288 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1289 return RawFlags;
1290}
1291
1293 uint64_t RawFlags = 0;
1294
1295 RawFlags |= CI.Hotness; // 3 bits
1296 RawFlags |= (CI.HasTailCall << 3); // 1 bit
1297
1298 return RawFlags;
1299}
1300
1302 uint64_t RawFlags = 0;
1303
1304 RawFlags |= CI.RelBlockFreq; // CalleeInfo::RelBlockFreqBits bits
1305 RawFlags |= (CI.HasTailCall << CalleeInfo::RelBlockFreqBits); // 1 bit
1306
1307 return RawFlags;
1308}
1309
1310static unsigned getEncodedVisibility(const GlobalValue &GV) {
1311 switch (GV.getVisibility()) {
1312 case GlobalValue::DefaultVisibility: return 0;
1313 case GlobalValue::HiddenVisibility: return 1;
1314 case GlobalValue::ProtectedVisibility: return 2;
1315 }
1316 llvm_unreachable("Invalid visibility");
1317}
1318
1319static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1320 switch (GV.getDLLStorageClass()) {
1321 case GlobalValue::DefaultStorageClass: return 0;
1324 }
1325 llvm_unreachable("Invalid DLL storage class");
1326}
1327
1328static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1329 switch (GV.getThreadLocalMode()) {
1330 case GlobalVariable::NotThreadLocal: return 0;
1331 case GlobalVariable::GeneralDynamicTLSModel: return 1;
1332 case GlobalVariable::LocalDynamicTLSModel: return 2;
1333 case GlobalVariable::InitialExecTLSModel: return 3;
1334 case GlobalVariable::LocalExecTLSModel: return 4;
1335 }
1336 llvm_unreachable("Invalid TLS model");
1337}
1338
1339static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1340 switch (C.getSelectionKind()) {
1341 case Comdat::Any:
1343 case Comdat::ExactMatch:
1345 case Comdat::Largest:
1349 case Comdat::SameSize:
1351 }
1352 llvm_unreachable("Invalid selection kind");
1353}
1354
1355static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1356 switch (GV.getUnnamedAddr()) {
1357 case GlobalValue::UnnamedAddr::None: return 0;
1358 case GlobalValue::UnnamedAddr::Local: return 2;
1359 case GlobalValue::UnnamedAddr::Global: return 1;
1360 }
1361 llvm_unreachable("Invalid unnamed_addr");
1362}
1363
1364size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1365 if (GenerateHash)
1366 Hasher.update(Str);
1367 return StrtabBuilder.add(Str);
1368}
1369
1370void ModuleBitcodeWriter::writeComdats() {
1372 for (const Comdat *C : VE.getComdats()) {
1373 // COMDAT: [strtab offset, strtab size, selection_kind]
1374 Vals.push_back(addToStrtab(C->getName()));
1375 Vals.push_back(C->getName().size());
1377 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1378 Vals.clear();
1379 }
1380}
1381
1382/// Write a record that will eventually hold the word offset of the
1383/// module-level VST. For now the offset is 0, which will be backpatched
1384/// after the real VST is written. Saves the bit offset to backpatch.
1385void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1386 // Write a placeholder value in for the offset of the real VST,
1387 // which is written after the function blocks so that it can include
1388 // the offset of each function. The placeholder offset will be
1389 // updated when the real VST is written.
1390 auto Abbv = std::make_shared<BitCodeAbbrev>();
1392 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1393 // hold the real VST offset. Must use fixed instead of VBR as we don't
1394 // know how many VBR chunks to reserve ahead of time.
1396 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1397
1398 // Emit the placeholder
1400 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1401
1402 // Compute and save the bit offset to the placeholder, which will be
1403 // patched when the real VST is written. We can simply subtract the 32-bit
1404 // fixed size from the current bit number to get the location to backpatch.
1405 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1406}
1407
1409
1410/// Determine the encoding to use for the given string name and length.
1412 bool isChar6 = true;
1413 for (char C : Str) {
1414 if (isChar6)
1415 isChar6 = BitCodeAbbrevOp::isChar6(C);
1416 if ((unsigned char)C & 128)
1417 // don't bother scanning the rest.
1418 return SE_Fixed8;
1419 }
1420 if (isChar6)
1421 return SE_Char6;
1422 return SE_Fixed7;
1423}
1424
1425static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
1426 "Sanitizer Metadata is too large for naive serialization.");
1427static unsigned
1429 return Meta.NoAddress | (Meta.NoHWAddress << 1) |
1430 (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
1431}
1432
1433/// Emit top-level description of module, including target triple, inline asm,
1434/// descriptors for global variables, and function prototype info.
1435/// Returns the bit offset to backpatch with the location of the real VST.
1436void ModuleBitcodeWriter::writeModuleInfo() {
1437 // Emit various pieces of data attached to a module.
1438 if (!M.getTargetTriple().empty())
1439 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1440 0 /*TODO*/);
1441 const std::string &DL = M.getDataLayoutStr();
1442 if (!DL.empty())
1444 if (!M.getModuleInlineAsm().empty())
1445 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1446 0 /*TODO*/);
1447
1448 // Emit information about sections and GC, computing how many there are. Also
1449 // compute the maximum alignment value.
1450 std::map<std::string, unsigned> SectionMap;
1451 std::map<std::string, unsigned> GCMap;
1452 MaybeAlign MaxAlignment;
1453 unsigned MaxGlobalType = 0;
1454 const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1455 if (A)
1456 MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1457 };
1458 for (const GlobalVariable &GV : M.globals()) {
1459 UpdateMaxAlignment(GV.getAlign());
1460 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1461 if (GV.hasSection()) {
1462 // Give section names unique ID's.
1463 unsigned &Entry = SectionMap[std::string(GV.getSection())];
1464 if (!Entry) {
1465 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1466 0 /*TODO*/);
1467 Entry = SectionMap.size();
1468 }
1469 }
1470 }
1471 for (const Function &F : M) {
1472 UpdateMaxAlignment(F.getAlign());
1473 if (F.hasSection()) {
1474 // Give section names unique ID's.
1475 unsigned &Entry = SectionMap[std::string(F.getSection())];
1476 if (!Entry) {
1478 0 /*TODO*/);
1479 Entry = SectionMap.size();
1480 }
1481 }
1482 if (F.hasGC()) {
1483 // Same for GC names.
1484 unsigned &Entry = GCMap[F.getGC()];
1485 if (!Entry) {
1487 0 /*TODO*/);
1488 Entry = GCMap.size();
1489 }
1490 }
1491 }
1492
1493 // Emit abbrev for globals, now that we know # sections and max alignment.
1494 unsigned SimpleGVarAbbrev = 0;
1495 if (!M.global_empty()) {
1496 // Add an abbrev for common globals with no visibility or thread localness.
1497 auto Abbv = std::make_shared<BitCodeAbbrev>();
1502 Log2_32_Ceil(MaxGlobalType+1)));
1503 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1504 //| explicitType << 1
1505 //| constant
1506 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1507 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1508 if (!MaxAlignment) // Alignment.
1509 Abbv->Add(BitCodeAbbrevOp(0));
1510 else {
1511 unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
1513 Log2_32_Ceil(MaxEncAlignment+1)));
1514 }
1515 if (SectionMap.empty()) // Section.
1516 Abbv->Add(BitCodeAbbrevOp(0));
1517 else
1519 Log2_32_Ceil(SectionMap.size()+1)));
1520 // Don't bother emitting vis + thread local.
1521 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1522 }
1523
1525 // Emit the module's source file name.
1526 {
1527 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1529 if (Bits == SE_Char6)
1530 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1531 else if (Bits == SE_Fixed7)
1532 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1533
1534 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1535 auto Abbv = std::make_shared<BitCodeAbbrev>();
1538 Abbv->Add(AbbrevOpToUse);
1539 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1540
1541 for (const auto P : M.getSourceFileName())
1542 Vals.push_back((unsigned char)P);
1543
1544 // Emit the finished record.
1545 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1546 Vals.clear();
1547 }
1548
1549 // Emit the global variable information.
1550 for (const GlobalVariable &GV : M.globals()) {
1551 unsigned AbbrevToUse = 0;
1552
1553 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1554 // linkage, alignment, section, visibility, threadlocal,
1555 // unnamed_addr, externally_initialized, dllstorageclass,
1556 // comdat, attributes, DSO_Local, GlobalSanitizer, code_model]
1557 Vals.push_back(addToStrtab(GV.getName()));
1558 Vals.push_back(GV.getName().size());
1559 Vals.push_back(VE.getTypeID(GV.getValueType()));
1560 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1561 Vals.push_back(GV.isDeclaration() ? 0 :
1562 (VE.getValueID(GV.getInitializer()) + 1));
1563 Vals.push_back(getEncodedLinkage(GV));
1564 Vals.push_back(getEncodedAlign(GV.getAlign()));
1565 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1566 : 0);
1567 if (GV.isThreadLocal() ||
1568 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1569 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1570 GV.isExternallyInitialized() ||
1571 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1572 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1573 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1577 Vals.push_back(GV.isExternallyInitialized());
1579 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1580
1581 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1582 Vals.push_back(VE.getAttributeListID(AL));
1583
1584 Vals.push_back(GV.isDSOLocal());
1585 Vals.push_back(addToStrtab(GV.getPartition()));
1586 Vals.push_back(GV.getPartition().size());
1587
1588 Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
1589 GV.getSanitizerMetadata())
1590 : 0));
1591 Vals.push_back(GV.getCodeModelRaw());
1592 } else {
1593 AbbrevToUse = SimpleGVarAbbrev;
1594 }
1595
1596 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1597 Vals.clear();
1598 }
1599
1600 // Emit the function proto information.
1601 for (const Function &F : M) {
1602 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1603 // linkage, paramattrs, alignment, section, visibility, gc,
1604 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1605 // prefixdata, personalityfn, DSO_Local, addrspace]
1606 Vals.push_back(addToStrtab(F.getName()));
1607 Vals.push_back(F.getName().size());
1608 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1609 Vals.push_back(F.getCallingConv());
1610 Vals.push_back(F.isDeclaration());
1612 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1613 Vals.push_back(getEncodedAlign(F.getAlign()));
1614 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1615 : 0);
1617 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1619 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1620 : 0);
1622 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1623 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1624 : 0);
1625 Vals.push_back(
1626 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1627
1628 Vals.push_back(F.isDSOLocal());
1629 Vals.push_back(F.getAddressSpace());
1630 Vals.push_back(addToStrtab(F.getPartition()));
1631 Vals.push_back(F.getPartition().size());
1632
1633 unsigned AbbrevToUse = 0;
1634 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1635 Vals.clear();
1636 }
1637
1638 // Emit the alias information.
1639 for (const GlobalAlias &A : M.aliases()) {
1640 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1641 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1642 // DSO_Local]
1643 Vals.push_back(addToStrtab(A.getName()));
1644 Vals.push_back(A.getName().size());
1645 Vals.push_back(VE.getTypeID(A.getValueType()));
1646 Vals.push_back(A.getType()->getAddressSpace());
1647 Vals.push_back(VE.getValueID(A.getAliasee()));
1653 Vals.push_back(A.isDSOLocal());
1654 Vals.push_back(addToStrtab(A.getPartition()));
1655 Vals.push_back(A.getPartition().size());
1656
1657 unsigned AbbrevToUse = 0;
1658 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1659 Vals.clear();
1660 }
1661
1662 // Emit the ifunc information.
1663 for (const GlobalIFunc &I : M.ifuncs()) {
1664 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1665 // val#, linkage, visibility, DSO_Local]
1666 Vals.push_back(addToStrtab(I.getName()));
1667 Vals.push_back(I.getName().size());
1668 Vals.push_back(VE.getTypeID(I.getValueType()));
1669 Vals.push_back(I.getType()->getAddressSpace());
1670 Vals.push_back(VE.getValueID(I.getResolver()));
1673 Vals.push_back(I.isDSOLocal());
1674 Vals.push_back(addToStrtab(I.getPartition()));
1675 Vals.push_back(I.getPartition().size());
1676 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1677 Vals.clear();
1678 }
1679
1680 writeValueSymbolTableForwardDecl();
1681}
1682
1684 uint64_t Flags = 0;
1685
1686 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1687 if (OBO->hasNoSignedWrap())
1688 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1689 if (OBO->hasNoUnsignedWrap())
1690 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1691 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1692 if (PEO->isExact())
1693 Flags |= 1 << bitc::PEO_EXACT;
1694 } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {
1695 if (PDI->isDisjoint())
1696 Flags |= 1 << bitc::PDI_DISJOINT;
1697 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1698 if (FPMO->hasAllowReassoc())
1699 Flags |= bitc::AllowReassoc;
1700 if (FPMO->hasNoNaNs())
1701 Flags |= bitc::NoNaNs;
1702 if (FPMO->hasNoInfs())
1703 Flags |= bitc::NoInfs;
1704 if (FPMO->hasNoSignedZeros())
1705 Flags |= bitc::NoSignedZeros;
1706 if (FPMO->hasAllowReciprocal())
1707 Flags |= bitc::AllowReciprocal;
1708 if (FPMO->hasAllowContract())
1709 Flags |= bitc::AllowContract;
1710 if (FPMO->hasApproxFunc())
1711 Flags |= bitc::ApproxFunc;
1712 } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1713 if (NNI->hasNonNeg())
1714 Flags |= 1 << bitc::PNNI_NON_NEG;
1715 } else if (const auto *TI = dyn_cast<TruncInst>(V)) {
1716 if (TI->hasNoSignedWrap())
1717 Flags |= 1 << bitc::TIO_NO_SIGNED_WRAP;
1718 if (TI->hasNoUnsignedWrap())
1719 Flags |= 1 << bitc::TIO_NO_UNSIGNED_WRAP;
1720 } else if (const auto *GEP = dyn_cast<GEPOperator>(V)) {
1721 if (GEP->isInBounds())
1722 Flags |= 1 << bitc::GEP_INBOUNDS;
1723 if (GEP->hasNoUnsignedSignedWrap())
1724 Flags |= 1 << bitc::GEP_NUSW;
1725 if (GEP->hasNoUnsignedWrap())
1726 Flags |= 1 << bitc::GEP_NUW;
1727 } else if (const auto *ICmp = dyn_cast<ICmpInst>(V)) {
1728 if (ICmp->hasSameSign())
1729 Flags |= 1 << bitc::ICMP_SAME_SIGN;
1730 }
1731
1732 return Flags;
1733}
1734
1735void ModuleBitcodeWriter::writeValueAsMetadata(
1737 // Mimic an MDNode with a value as one operand.
1738 Value *V = MD->getValue();
1739 Record.push_back(VE.getTypeID(V->getType()));
1740 Record.push_back(VE.getValueID(V));
1742 Record.clear();
1743}
1744
1745void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1747 unsigned Abbrev) {
1748 for (const MDOperand &MDO : N->operands()) {
1749 Metadata *MD = MDO;
1750 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1751 "Unexpected function-local metadata");
1752 Record.push_back(VE.getMetadataOrNullID(MD));
1753 }
1754 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1756 Record, Abbrev);
1757 Record.clear();
1758}
1759
1760unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1761 // Assume the column is usually under 128, and always output the inlined-at
1762 // location (it's never more expensive than building an array size 1).
1763 auto Abbv = std::make_shared<BitCodeAbbrev>();
1771 return Stream.EmitAbbrev(std::move(Abbv));
1772}
1773
1774void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1776 unsigned &Abbrev) {
1777 if (!Abbrev)
1778 Abbrev = createDILocationAbbrev();
1779
1780 Record.push_back(N->isDistinct());
1781 Record.push_back(N->getLine());
1782 Record.push_back(N->getColumn());
1783 Record.push_back(VE.getMetadataID(N->getScope()));
1784 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1785 Record.push_back(N->isImplicitCode());
1786
1787 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1788 Record.clear();
1789}
1790
1791unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1792 // Assume the column is usually under 128, and always output the inlined-at
1793 // location (it's never more expensive than building an array size 1).
1794 auto Abbv = std::make_shared<BitCodeAbbrev>();
1802 return Stream.EmitAbbrev(std::move(Abbv));
1803}
1804
1805void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1807 unsigned &Abbrev) {
1808 if (!Abbrev)
1809 Abbrev = createGenericDINodeAbbrev();
1810
1811 Record.push_back(N->isDistinct());
1812 Record.push_back(N->getTag());
1813 Record.push_back(0); // Per-tag version field; unused for now.
1814
1815 for (auto &I : N->operands())
1816 Record.push_back(VE.getMetadataOrNullID(I));
1817
1819 Record.clear();
1820}
1821
1822void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1824 unsigned Abbrev) {
1825 const uint64_t Version = 2 << 1;
1826 Record.push_back((uint64_t)N->isDistinct() | Version);
1827 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1828 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1829 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1830 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1831
1832 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1833 Record.clear();
1834}
1835
1836void ModuleBitcodeWriter::writeDIGenericSubrange(
1838 unsigned Abbrev) {
1839 Record.push_back((uint64_t)N->isDistinct());
1840 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1841 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1842 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1843 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1844
1846 Record.clear();
1847}
1848
1849void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1851 unsigned Abbrev) {
1852 const uint64_t IsBigInt = 1 << 2;
1853 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
1854 Record.push_back(N->getValue().getBitWidth());
1855 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1856 emitWideAPInt(Record, N->getValue());
1857
1859 Record.clear();
1860}
1861
1862void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1864 unsigned Abbrev) {
1865 Record.push_back(N->isDistinct());
1866 Record.push_back(N->getTag());
1867 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1868 Record.push_back(N->getSizeInBits());
1869 Record.push_back(N->getAlignInBits());
1870 Record.push_back(N->getEncoding());
1871 Record.push_back(N->getFlags());
1872 Record.push_back(N->getNumExtraInhabitants());
1873
1875 Record.clear();
1876}
1877
1878void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
1880 unsigned Abbrev) {
1881 Record.push_back(N->isDistinct());
1882 Record.push_back(N->getTag());
1883 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1884 Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1885 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
1886 Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
1887 Record.push_back(N->getSizeInBits());
1888 Record.push_back(N->getAlignInBits());
1889 Record.push_back(N->getEncoding());
1890
1892 Record.clear();
1893}
1894
1895void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1897 unsigned Abbrev) {
1898 Record.push_back(N->isDistinct());
1899 Record.push_back(N->getTag());
1900 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1901 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1902 Record.push_back(N->getLine());
1903 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1904 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1905 Record.push_back(N->getSizeInBits());
1906 Record.push_back(N->getAlignInBits());
1907 Record.push_back(N->getOffsetInBits());
1908 Record.push_back(N->getFlags());
1909 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1910
1911 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1912 // that there is no DWARF address space associated with DIDerivedType.
1913 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1914 Record.push_back(*DWARFAddressSpace + 1);
1915 else
1916 Record.push_back(0);
1917
1918 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1919
1920 if (auto PtrAuthData = N->getPtrAuthData())
1921 Record.push_back(PtrAuthData->RawData);
1922 else
1923 Record.push_back(0);
1924
1926 Record.clear();
1927}
1928
1929void ModuleBitcodeWriter::writeDICompositeType(
1931 unsigned Abbrev) {
1932 const unsigned IsNotUsedInOldTypeRef = 0x2;
1933 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1934 Record.push_back(N->getTag());
1935 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1936 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1937 Record.push_back(N->getLine());
1938 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1939 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1940 Record.push_back(N->getSizeInBits());
1941 Record.push_back(N->getAlignInBits());
1942 Record.push_back(N->getOffsetInBits());
1943 Record.push_back(N->getFlags());
1944 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1945 Record.push_back(N->getRuntimeLang());
1946 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1947 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1948 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1949 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
1950 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1951 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1952 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1953 Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
1954 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1955 Record.push_back(N->getNumExtraInhabitants());
1956 Record.push_back(VE.getMetadataOrNullID(N->getRawSpecification()));
1957
1959 Record.clear();
1960}
1961
1962void ModuleBitcodeWriter::writeDISubroutineType(
1964 unsigned Abbrev) {
1965 const unsigned HasNoOldTypeRefs = 0x2;
1966 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1967 Record.push_back(N->getFlags());
1968 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1969 Record.push_back(N->getCC());
1970
1972 Record.clear();
1973}
1974
1975void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1977 unsigned Abbrev) {
1978 Record.push_back(N->isDistinct());
1979 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1980 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1981 if (N->getRawChecksum()) {
1982 Record.push_back(N->getRawChecksum()->Kind);
1983 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1984 } else {
1985 // Maintain backwards compatibility with the old internal representation of
1986 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1987 Record.push_back(0);
1988 Record.push_back(VE.getMetadataOrNullID(nullptr));
1989 }
1990 auto Source = N->getRawSource();
1991 if (Source)
1992 Record.push_back(VE.getMetadataOrNullID(Source));
1993
1994 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1995 Record.clear();
1996}
1997
1998void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
2000 unsigned Abbrev) {
2001 assert(N->isDistinct() && "Expected distinct compile units");
2002 Record.push_back(/* IsDistinct */ true);
2003 Record.push_back(N->getSourceLanguage());
2004 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2005 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
2006 Record.push_back(N->isOptimized());
2007 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
2008 Record.push_back(N->getRuntimeVersion());
2009 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
2010 Record.push_back(N->getEmissionKind());
2011 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
2012 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
2013 Record.push_back(/* subprograms */ 0);
2014 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
2015 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
2016 Record.push_back(N->getDWOId());
2017 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
2018 Record.push_back(N->getSplitDebugInlining());
2019 Record.push_back(N->getDebugInfoForProfiling());
2020 Record.push_back((unsigned)N->getNameTableKind());
2021 Record.push_back(N->getRangesBaseAddress());
2022 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
2023 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
2024
2026 Record.clear();
2027}
2028
2029void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
2031 unsigned Abbrev) {
2032 const uint64_t HasUnitFlag = 1 << 1;
2033 const uint64_t HasSPFlagsFlag = 1 << 2;
2034 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2035 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2036 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2037 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2038 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2039 Record.push_back(N->getLine());
2040 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2041 Record.push_back(N->getScopeLine());
2042 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
2043 Record.push_back(N->getSPFlags());
2044 Record.push_back(N->getVirtualIndex());
2045 Record.push_back(N->getFlags());
2046 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
2047 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2048 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
2049 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
2050 Record.push_back(N->getThisAdjustment());
2051 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
2052 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2053 Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
2054
2056 Record.clear();
2057}
2058
2059void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
2061 unsigned Abbrev) {
2062 Record.push_back(N->isDistinct());
2063 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2064 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2065 Record.push_back(N->getLine());
2066 Record.push_back(N->getColumn());
2067
2069 Record.clear();
2070}
2071
2072void ModuleBitcodeWriter::writeDILexicalBlockFile(
2074 unsigned Abbrev) {
2075 Record.push_back(N->isDistinct());
2076 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2077 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2078 Record.push_back(N->getDiscriminator());
2079
2081 Record.clear();
2082}
2083
2084void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
2086 unsigned Abbrev) {
2087 Record.push_back(N->isDistinct());
2088 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2089 Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
2090 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2091 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2092 Record.push_back(N->getLineNo());
2093
2095 Record.clear();
2096}
2097
2098void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
2100 unsigned Abbrev) {
2101 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
2102 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2103 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2104
2106 Record.clear();
2107}
2108
2109void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
2111 unsigned Abbrev) {
2112 Record.push_back(N->isDistinct());
2113 Record.push_back(N->getMacinfoType());
2114 Record.push_back(N->getLine());
2115 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2116 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
2117
2118 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
2119 Record.clear();
2120}
2121
2122void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
2124 unsigned Abbrev) {
2125 Record.push_back(N->isDistinct());
2126 Record.push_back(N->getMacinfoType());
2127 Record.push_back(N->getLine());
2128 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2129 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2130
2132 Record.clear();
2133}
2134
2135void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
2137 Record.reserve(N->getArgs().size());
2138 for (ValueAsMetadata *MD : N->getArgs())
2139 Record.push_back(VE.getMetadataID(MD));
2140
2142 Record.clear();
2143}
2144
2145void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
2147 unsigned Abbrev) {
2148 Record.push_back(N->isDistinct());
2149 for (auto &I : N->operands())
2150 Record.push_back(VE.getMetadataOrNullID(I));
2151 Record.push_back(N->getLineNo());
2152 Record.push_back(N->getIsDecl());
2153
2154 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
2155 Record.clear();
2156}
2157
2158void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
2160 unsigned Abbrev) {
2161 // There are no arguments for this metadata type.
2162 Record.push_back(N->isDistinct());
2164 Record.clear();
2165}
2166
2167void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2169 unsigned Abbrev) {
2170 Record.push_back(N->isDistinct());
2171 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2172 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2173 Record.push_back(N->isDefault());
2174
2176 Record.clear();
2177}
2178
2179void ModuleBitcodeWriter::writeDITemplateValueParameter(
2181 unsigned Abbrev) {
2182 Record.push_back(N->isDistinct());
2183 Record.push_back(N->getTag());
2184 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2185 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2186 Record.push_back(N->isDefault());
2187 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
2188
2190 Record.clear();
2191}
2192
2193void ModuleBitcodeWriter::writeDIGlobalVariable(
2195 unsigned Abbrev) {
2196 const uint64_t Version = 2 << 1;
2197 Record.push_back((uint64_t)N->isDistinct() | Version);
2198 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2199 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2200 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2201 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2202 Record.push_back(N->getLine());
2203 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2204 Record.push_back(N->isLocalToUnit());
2205 Record.push_back(N->isDefinition());
2206 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
2207 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
2208 Record.push_back(N->getAlignInBits());
2209 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2210
2212 Record.clear();
2213}
2214
2215void ModuleBitcodeWriter::writeDILocalVariable(
2217 unsigned Abbrev) {
2218 // In order to support all possible bitcode formats in BitcodeReader we need
2219 // to distinguish the following cases:
2220 // 1) Record has no artificial tag (Record[1]),
2221 // has no obsolete inlinedAt field (Record[9]).
2222 // In this case Record size will be 8, HasAlignment flag is false.
2223 // 2) Record has artificial tag (Record[1]),
2224 // has no obsolete inlignedAt field (Record[9]).
2225 // In this case Record size will be 9, HasAlignment flag is false.
2226 // 3) Record has both artificial tag (Record[1]) and
2227 // obsolete inlignedAt field (Record[9]).
2228 // In this case Record size will be 10, HasAlignment flag is false.
2229 // 4) Record has neither artificial tag, nor inlignedAt field, but
2230 // HasAlignment flag is true and Record[8] contains alignment value.
2231 const uint64_t HasAlignmentFlag = 1 << 1;
2232 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2233 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2234 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2235 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2236 Record.push_back(N->getLine());
2237 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2238 Record.push_back(N->getArg());
2239 Record.push_back(N->getFlags());
2240 Record.push_back(N->getAlignInBits());
2241 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2242
2244 Record.clear();
2245}
2246
2247void ModuleBitcodeWriter::writeDILabel(
2249 unsigned Abbrev) {
2250 Record.push_back((uint64_t)N->isDistinct());
2251 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2252 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2253 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2254 Record.push_back(N->getLine());
2255
2256 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2257 Record.clear();
2258}
2259
2260void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
2262 unsigned Abbrev) {
2263 Record.reserve(N->getElements().size() + 1);
2264 const uint64_t Version = 3 << 1;
2265 Record.push_back((uint64_t)N->isDistinct() | Version);
2266 Record.append(N->elements_begin(), N->elements_end());
2267
2269 Record.clear();
2270}
2271
2272void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2274 unsigned Abbrev) {
2275 Record.push_back(N->isDistinct());
2276 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2277 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2278
2280 Record.clear();
2281}
2282
2283void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
2285 unsigned Abbrev) {
2286 Record.push_back(N->isDistinct());
2287 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2288 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2289 Record.push_back(N->getLine());
2290 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2291 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2292 Record.push_back(N->getAttributes());
2293 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2294
2296 Record.clear();
2297}
2298
2299void ModuleBitcodeWriter::writeDIImportedEntity(
2301 unsigned Abbrev) {
2302 Record.push_back(N->isDistinct());
2303 Record.push_back(N->getTag());
2304 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2305 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2306 Record.push_back(N->getLine());
2307 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2308 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2309 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2310
2312 Record.clear();
2313}
2314
2315unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2316 auto Abbv = std::make_shared<BitCodeAbbrev>();
2320 return Stream.EmitAbbrev(std::move(Abbv));
2321}
2322
2323void ModuleBitcodeWriter::writeNamedMetadata(
2325 if (M.named_metadata_empty())
2326 return;
2327
2328 unsigned Abbrev = createNamedMetadataAbbrev();
2329 for (const NamedMDNode &NMD : M.named_metadata()) {
2330 // Write name.
2331 StringRef Str = NMD.getName();
2332 Record.append(Str.bytes_begin(), Str.bytes_end());
2333 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2334 Record.clear();
2335
2336 // Write named metadata operands.
2337 for (const MDNode *N : NMD.operands())
2338 Record.push_back(VE.getMetadataID(N));
2340 Record.clear();
2341 }
2342}
2343
2344unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2345 auto Abbv = std::make_shared<BitCodeAbbrev>();
2347 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2348 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2350 return Stream.EmitAbbrev(std::move(Abbv));
2351}
2352
2353/// Write out a record for MDString.
2354///
2355/// All the metadata strings in a metadata block are emitted in a single
2356/// record. The sizes and strings themselves are shoved into a blob.
2357void ModuleBitcodeWriter::writeMetadataStrings(
2359 if (Strings.empty())
2360 return;
2361
2362 // Start the record with the number of strings.
2363 Record.push_back(bitc::METADATA_STRINGS);
2364 Record.push_back(Strings.size());
2365
2366 // Emit the sizes of the strings in the blob.
2367 SmallString<256> Blob;
2368 {
2369 BitstreamWriter W(Blob);
2370 for (const Metadata *MD : Strings)
2371 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2372 W.FlushToWord();
2373 }
2374
2375 // Add the offset to the strings to the record.
2376 Record.push_back(Blob.size());
2377
2378 // Add the strings to the blob.
2379 for (const Metadata *MD : Strings)
2380 Blob.append(cast<MDString>(MD)->getString());
2381
2382 // Emit the final record.
2383 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2384 Record.clear();
2385}
2386
2387// Generates an enum to use as an index in the Abbrev array of Metadata record.
2388enum MetadataAbbrev : unsigned {
2389#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2390#include "llvm/IR/Metadata.def"
2393
2394void ModuleBitcodeWriter::writeMetadataRecords(
2396 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2397 if (MDs.empty())
2398 return;
2399
2400 // Initialize MDNode abbreviations.
2401#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2402#include "llvm/IR/Metadata.def"
2403
2404 for (const Metadata *MD : MDs) {
2405 if (IndexPos)
2406 IndexPos->push_back(Stream.GetCurrentBitNo());
2407 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2408 assert(N->isResolved() && "Expected forward references to be resolved");
2409
2410 switch (N->getMetadataID()) {
2411 default:
2412 llvm_unreachable("Invalid MDNode subclass");
2413#define HANDLE_MDNODE_LEAF(CLASS) \
2414 case Metadata::CLASS##Kind: \
2415 if (MDAbbrevs) \
2416 write##CLASS(cast<CLASS>(N), Record, \
2417 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2418 else \
2419 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2420 continue;
2421#include "llvm/IR/Metadata.def"
2422 }
2423 }
2424 if (auto *AL = dyn_cast<DIArgList>(MD)) {
2426 continue;
2427 }
2428 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2429 }
2430}
2431
2432void ModuleBitcodeWriter::writeModuleMetadata() {
2433 if (!VE.hasMDs() && M.named_metadata_empty())
2434 return;
2435
2438
2439 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2440 // block and load any metadata.
2441 std::vector<unsigned> MDAbbrevs;
2442
2443 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2444 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2445 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2446 createGenericDINodeAbbrev();
2447
2448 auto Abbv = std::make_shared<BitCodeAbbrev>();
2452 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2453
2454 Abbv = std::make_shared<BitCodeAbbrev>();
2458 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2459
2460 // Emit MDStrings together upfront.
2461 writeMetadataStrings(VE.getMDStrings(), Record);
2462
2463 // We only emit an index for the metadata record if we have more than a given
2464 // (naive) threshold of metadatas, otherwise it is not worth it.
2465 if (VE.getNonMDStrings().size() > IndexThreshold) {
2466 // Write a placeholder value in for the offset of the metadata index,
2467 // which is written after the records, so that it can include
2468 // the offset of each entry. The placeholder offset will be
2469 // updated after all records are emitted.
2470 uint64_t Vals[] = {0, 0};
2471 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2472 }
2473
2474 // Compute and save the bit offset to the current position, which will be
2475 // patched when we emit the index later. We can simply subtract the 64-bit
2476 // fixed size from the current bit number to get the location to backpatch.
2477 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2478
2479 // This index will contain the bitpos for each individual record.
2480 std::vector<uint64_t> IndexPos;
2481 IndexPos.reserve(VE.getNonMDStrings().size());
2482
2483 // Write all the records
2484 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2485
2486 if (VE.getNonMDStrings().size() > IndexThreshold) {
2487 // Now that we have emitted all the records we will emit the index. But
2488 // first
2489 // backpatch the forward reference so that the reader can skip the records
2490 // efficiently.
2491 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2492 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2493
2494 // Delta encode the index.
2495 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2496 for (auto &Elt : IndexPos) {
2497 auto EltDelta = Elt - PreviousValue;
2498 PreviousValue = Elt;
2499 Elt = EltDelta;
2500 }
2501 // Emit the index record.
2502 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2503 IndexPos.clear();
2504 }
2505
2506 // Write the named metadata now.
2507 writeNamedMetadata(Record);
2508
2509 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2511 Record.push_back(VE.getValueID(&GO));
2512 pushGlobalMetadataAttachment(Record, GO);
2514 };
2515 for (const Function &F : M)
2516 if (F.isDeclaration() && F.hasMetadata())
2517 AddDeclAttachedMetadata(F);
2518 // FIXME: Only store metadata for declarations here, and move data for global
2519 // variable definitions to a separate block (PR28134).
2520 for (const GlobalVariable &GV : M.globals())
2521 if (GV.hasMetadata())
2522 AddDeclAttachedMetadata(GV);
2523
2524 Stream.ExitBlock();
2525}
2526
2527void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2528 if (!VE.hasMDs())
2529 return;
2530
2533 writeMetadataStrings(VE.getMDStrings(), Record);
2534 writeMetadataRecords(VE.getNonMDStrings(), Record);
2535 Stream.ExitBlock();
2536}
2537
2538void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2540 // [n x [id, mdnode]]
2542 GO.getAllMetadata(MDs);
2543 for (const auto &I : MDs) {
2544 Record.push_back(I.first);
2545 Record.push_back(VE.getMetadataID(I.second));
2546 }
2547}
2548
2549void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2551
2553
2554 if (F.hasMetadata()) {
2555 pushGlobalMetadataAttachment(Record, F);
2557 Record.clear();
2558 }
2559
2560 // Write metadata attachments
2561 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2563 for (const BasicBlock &BB : F)
2564 for (const Instruction &I : BB) {
2565 MDs.clear();
2566 I.getAllMetadataOtherThanDebugLoc(MDs);
2567
2568 // If no metadata, ignore instruction.
2569 if (MDs.empty()) continue;
2570
2571 Record.push_back(VE.getInstructionID(&I));
2572
2573 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2574 Record.push_back(MDs[i].first);
2575 Record.push_back(VE.getMetadataID(MDs[i].second));
2576 }
2578 Record.clear();
2579 }
2580
2581 Stream.ExitBlock();
2582}
2583
2584void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2586
2587 // Write metadata kinds
2588 // METADATA_KIND - [n x [id, name]]
2590 M.getMDKindNames(Names);
2591
2592 if (Names.empty()) return;
2593
2595
2596 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2597 Record.push_back(MDKindID);
2598 StringRef KName = Names[MDKindID];
2599 Record.append(KName.begin(), KName.end());
2600
2602 Record.clear();
2603 }
2604
2605 Stream.ExitBlock();
2606}
2607
2608void ModuleBitcodeWriter::writeOperandBundleTags() {
2609 // Write metadata kinds
2610 //
2611 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2612 //
2613 // OPERAND_BUNDLE_TAG - [strchr x N]
2614
2616 M.getOperandBundleTags(Tags);
2617
2618 if (Tags.empty())
2619 return;
2620
2622
2624
2625 for (auto Tag : Tags) {
2626 Record.append(Tag.begin(), Tag.end());
2627
2629 Record.clear();
2630 }
2631
2632 Stream.ExitBlock();
2633}
2634
2635void ModuleBitcodeWriter::writeSyncScopeNames() {
2637 M.getContext().getSyncScopeNames(SSNs);
2638 if (SSNs.empty())
2639 return;
2640
2642
2644 for (auto SSN : SSNs) {
2645 Record.append(SSN.begin(), SSN.end());
2647 Record.clear();
2648 }
2649
2650 Stream.ExitBlock();
2651}
2652
2653void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2654 bool isGlobal) {
2655 if (FirstVal == LastVal) return;
2656
2658
2659 unsigned AggregateAbbrev = 0;
2660 unsigned String8Abbrev = 0;
2661 unsigned CString7Abbrev = 0;
2662 unsigned CString6Abbrev = 0;
2663 // If this is a constant pool for the module, emit module-specific abbrevs.
2664 if (isGlobal) {
2665 // Abbrev for CST_CODE_AGGREGATE.
2666 auto Abbv = std::make_shared<BitCodeAbbrev>();
2669 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2670 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2671
2672 // Abbrev for CST_CODE_STRING.
2673 Abbv = std::make_shared<BitCodeAbbrev>();
2677 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2678 // Abbrev for CST_CODE_CSTRING.
2679 Abbv = std::make_shared<BitCodeAbbrev>();
2683 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2684 // Abbrev for CST_CODE_CSTRING.
2685 Abbv = std::make_shared<BitCodeAbbrev>();
2689 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2690 }
2691
2693
2694 const ValueEnumerator::ValueList &Vals = VE.getValues();
2695 Type *LastTy = nullptr;
2696 for (unsigned i = FirstVal; i != LastVal; ++i) {
2697 const Value *V = Vals[i].first;
2698 // If we need to switch types, do so now.
2699 if (V->getType() != LastTy) {
2700 LastTy = V->getType();
2701 Record.push_back(VE.getTypeID(LastTy));
2703 CONSTANTS_SETTYPE_ABBREV);
2704 Record.clear();
2705 }
2706
2707 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2708 Record.push_back(VE.getTypeID(IA->getFunctionType()));
2709 Record.push_back(
2710 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2711 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2712
2713 // Add the asm string.
2714 const std::string &AsmStr = IA->getAsmString();
2715 Record.push_back(AsmStr.size());
2716 Record.append(AsmStr.begin(), AsmStr.end());
2717
2718 // Add the constraint string.
2719 const std::string &ConstraintStr = IA->getConstraintString();
2720 Record.push_back(ConstraintStr.size());
2721 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2723 Record.clear();
2724 continue;
2725 }
2726 const Constant *C = cast<Constant>(V);
2727 unsigned Code = -1U;
2728 unsigned AbbrevToUse = 0;
2729 if (C->isNullValue()) {
2731 } else if (isa<PoisonValue>(C)) {
2733 } else if (isa<UndefValue>(C)) {
2735 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2736 if (IV->getBitWidth() <= 64) {
2737 uint64_t V = IV->getSExtValue();
2740 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2741 } else { // Wide integers, > 64 bits in size.
2742 emitWideAPInt(Record, IV->getValue());
2744 }
2745 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2747 Type *Ty = CFP->getType()->getScalarType();
2748 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2749 Ty->isDoubleTy()) {
2750 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2751 } else if (Ty->isX86_FP80Ty()) {
2752 // api needed to prevent premature destruction
2753 // bits are not in the same order as a normal i80 APInt, compensate.
2754 APInt api = CFP->getValueAPF().bitcastToAPInt();
2755 const uint64_t *p = api.getRawData();
2756 Record.push_back((p[1] << 48) | (p[0] >> 16));
2757 Record.push_back(p[0] & 0xffffLL);
2758 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2759 APInt api = CFP->getValueAPF().bitcastToAPInt();
2760 const uint64_t *p = api.getRawData();
2761 Record.push_back(p[0]);
2762 Record.push_back(p[1]);
2763 } else {
2764 assert(0 && "Unknown FP type!");
2765 }
2766 } else if (isa<ConstantDataSequential>(C) &&
2767 cast<ConstantDataSequential>(C)->isString()) {
2768 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2769 // Emit constant strings specially.
2770 unsigned NumElts = Str->getNumElements();
2771 // If this is a null-terminated string, use the denser CSTRING encoding.
2772 if (Str->isCString()) {
2774 --NumElts; // Don't encode the null, which isn't allowed by char6.
2775 } else {
2777 AbbrevToUse = String8Abbrev;
2778 }
2779 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2780 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2781 for (unsigned i = 0; i != NumElts; ++i) {
2782 unsigned char V = Str->getElementAsInteger(i);
2783 Record.push_back(V);
2784 isCStr7 &= (V & 128) == 0;
2785 if (isCStrChar6)
2786 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2787 }
2788
2789 if (isCStrChar6)
2790 AbbrevToUse = CString6Abbrev;
2791 else if (isCStr7)
2792 AbbrevToUse = CString7Abbrev;
2793 } else if (const ConstantDataSequential *CDS =
2794 dyn_cast<ConstantDataSequential>(C)) {
2796 Type *EltTy = CDS->getElementType();
2797 if (isa<IntegerType>(EltTy)) {
2798 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2799 Record.push_back(CDS->getElementAsInteger(i));
2800 } else {
2801 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2802 Record.push_back(
2803 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2804 }
2805 } else if (isa<ConstantAggregate>(C)) {
2807 for (const Value *Op : C->operands())
2808 Record.push_back(VE.getValueID(Op));
2809 AbbrevToUse = AggregateAbbrev;
2810 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2811 switch (CE->getOpcode()) {
2812 default:
2813 if (Instruction::isCast(CE->getOpcode())) {
2815 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2816 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2817 Record.push_back(VE.getValueID(C->getOperand(0)));
2818 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2819 } else {
2820 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2822 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2823 Record.push_back(VE.getValueID(C->getOperand(0)));
2824 Record.push_back(VE.getValueID(C->getOperand(1)));
2826 if (Flags != 0)
2827 Record.push_back(Flags);
2828 }
2829 break;
2830 case Instruction::FNeg: {
2831 assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2833 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2834 Record.push_back(VE.getValueID(C->getOperand(0)));
2836 if (Flags != 0)
2837 Record.push_back(Flags);
2838 break;
2839 }
2840 case Instruction::GetElementPtr: {
2842 const auto *GO = cast<GEPOperator>(C);
2843 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2844 Record.push_back(getOptimizationFlags(GO));
2845 if (std::optional<ConstantRange> Range = GO->getInRange()) {
2847 emitConstantRange(Record, *Range, /*EmitBitWidth=*/true);
2848 }
2849 for (const Value *Op : CE->operands()) {
2850 Record.push_back(VE.getTypeID(Op->getType()));
2851 Record.push_back(VE.getValueID(Op));
2852 }
2853 break;
2854 }
2855 case Instruction::ExtractElement:
2857 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2858 Record.push_back(VE.getValueID(C->getOperand(0)));
2859 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2860 Record.push_back(VE.getValueID(C->getOperand(1)));
2861 break;
2862 case Instruction::InsertElement:
2864 Record.push_back(VE.getValueID(C->getOperand(0)));
2865 Record.push_back(VE.getValueID(C->getOperand(1)));
2866 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2867 Record.push_back(VE.getValueID(C->getOperand(2)));
2868 break;
2869 case Instruction::ShuffleVector:
2870 // If the return type and argument types are the same, this is a
2871 // standard shufflevector instruction. If the types are different,
2872 // then the shuffle is widening or truncating the input vectors, and
2873 // the argument type must also be encoded.
2874 if (C->getType() == C->getOperand(0)->getType()) {
2876 } else {
2878 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2879 }
2880 Record.push_back(VE.getValueID(C->getOperand(0)));
2881 Record.push_back(VE.getValueID(C->getOperand(1)));
2882 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
2883 break;
2884 }
2885 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2887 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2888 Record.push_back(VE.getValueID(BA->getFunction()));
2889 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2890 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2892 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2893 Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
2894 } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
2896 Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
2897 Record.push_back(VE.getValueID(NC->getGlobalValue()));
2898 } else if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C)) {
2900 Record.push_back(VE.getValueID(CPA->getPointer()));
2901 Record.push_back(VE.getValueID(CPA->getKey()));
2902 Record.push_back(VE.getValueID(CPA->getDiscriminator()));
2903 Record.push_back(VE.getValueID(CPA->getAddrDiscriminator()));
2904 } else {
2905#ifndef NDEBUG
2906 C->dump();
2907#endif
2908 llvm_unreachable("Unknown constant!");
2909 }
2910 Stream.EmitRecord(Code, Record, AbbrevToUse);
2911 Record.clear();
2912 }
2913
2914 Stream.ExitBlock();
2915}
2916
2917void ModuleBitcodeWriter::writeModuleConstants() {
2918 const ValueEnumerator::ValueList &Vals = VE.getValues();
2919
2920 // Find the first constant to emit, which is the first non-globalvalue value.
2921 // We know globalvalues have been emitted by WriteModuleInfo.
2922 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2923 if (!isa<GlobalValue>(Vals[i].first)) {
2924 writeConstants(i, Vals.size(), true);
2925 return;
2926 }
2927 }
2928}
2929
2930/// pushValueAndType - The file has to encode both the value and type id for
2931/// many values, because we need to know what type to create for forward
2932/// references. However, most operands are not forward references, so this type
2933/// field is not needed.
2934///
2935/// This function adds V's value ID to Vals. If the value ID is higher than the
2936/// instruction ID, then it is a forward reference, and it also includes the
2937/// type ID. The value ID that is written is encoded relative to the InstID.
2938bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2940 unsigned ValID = VE.getValueID(V);
2941 // Make encoding relative to the InstID.
2942 Vals.push_back(InstID - ValID);
2943 if (ValID >= InstID) {
2944 Vals.push_back(VE.getTypeID(V->getType()));
2945 return true;
2946 }
2947 return false;
2948}
2949
2950bool ModuleBitcodeWriter::pushValueOrMetadata(const Value *V, unsigned InstID,
2952 bool IsMetadata = V->getType()->isMetadataTy();
2953 if (IsMetadata) {
2955 Metadata *MD = cast<MetadataAsValue>(V)->getMetadata();
2956 unsigned ValID = VE.getMetadataID(MD);
2957 Vals.push_back(InstID - ValID);
2958 return false;
2959 }
2960 return pushValueAndType(V, InstID, Vals);
2961}
2962
2963void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
2964 unsigned InstID) {
2966 LLVMContext &C = CS.getContext();
2967
2968 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2969 const auto &Bundle = CS.getOperandBundleAt(i);
2970 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2971
2972 for (auto &Input : Bundle.Inputs)
2973 pushValueOrMetadata(Input, InstID, Record);
2974
2976 Record.clear();
2977 }
2978}
2979
2980/// pushValue - Like pushValueAndType, but where the type of the value is
2981/// omitted (perhaps it was already encoded in an earlier operand).
2982void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2984 unsigned ValID = VE.getValueID(V);
2985 Vals.push_back(InstID - ValID);
2986}
2987
2988void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2990 unsigned ValID = VE.getValueID(V);
2991 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2992 emitSignedInt64(Vals, diff);
2993}
2994
2995/// WriteInstruction - Emit an instruction to the specified stream.
2996void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2997 unsigned InstID,
2999 unsigned Code = 0;
3000 unsigned AbbrevToUse = 0;
3001 VE.setInstructionID(&I);
3002 switch (I.getOpcode()) {
3003 default:
3004 if (Instruction::isCast(I.getOpcode())) {
3006 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3007 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3008 Vals.push_back(VE.getTypeID(I.getType()));
3009 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
3011 if (Flags != 0) {
3012 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3013 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3014 Vals.push_back(Flags);
3015 }
3016 } else {
3017 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
3019 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3020 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3021 pushValue(I.getOperand(1), InstID, Vals);
3022 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
3024 if (Flags != 0) {
3025 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3026 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3027 Vals.push_back(Flags);
3028 }
3029 }
3030 break;
3031 case Instruction::FNeg: {
3033 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3034 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3035 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
3037 if (Flags != 0) {
3038 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3039 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3040 Vals.push_back(Flags);
3041 }
3042 break;
3043 }
3044 case Instruction::GetElementPtr: {
3046 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3047 auto &GEPInst = cast<GetElementPtrInst>(I);
3049 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
3050 for (const Value *Op : I.operands())
3051 pushValueAndType(Op, InstID, Vals);
3052 break;
3053 }
3054 case Instruction::ExtractValue: {
3056 pushValueAndType(I.getOperand(0), InstID, Vals);
3057 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3058 Vals.append(EVI->idx_begin(), EVI->idx_end());
3059 break;
3060 }
3061 case Instruction::InsertValue: {
3063 pushValueAndType(I.getOperand(0), InstID, Vals);
3064 pushValueAndType(I.getOperand(1), InstID, Vals);
3065 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
3066 Vals.append(IVI->idx_begin(), IVI->idx_end());
3067 break;
3068 }
3069 case Instruction::Select: {
3071 pushValueAndType(I.getOperand(1), InstID, Vals);
3072 pushValue(I.getOperand(2), InstID, Vals);
3073 pushValueAndType(I.getOperand(0), InstID, Vals);
3075 if (Flags != 0)
3076 Vals.push_back(Flags);
3077 break;
3078 }
3079 case Instruction::ExtractElement:
3081 pushValueAndType(I.getOperand(0), InstID, Vals);
3082 pushValueAndType(I.getOperand(1), InstID, Vals);
3083 break;
3084 case Instruction::InsertElement:
3086 pushValueAndType(I.getOperand(0), InstID, Vals);
3087 pushValue(I.getOperand(1), InstID, Vals);
3088 pushValueAndType(I.getOperand(2), InstID, Vals);
3089 break;
3090 case Instruction::ShuffleVector:
3092 pushValueAndType(I.getOperand(0), InstID, Vals);
3093 pushValue(I.getOperand(1), InstID, Vals);
3094 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
3095 Vals);
3096 break;
3097 case Instruction::ICmp:
3098 case Instruction::FCmp: {
3099 // compare returning Int1Ty or vector of Int1Ty
3101 pushValueAndType(I.getOperand(0), InstID, Vals);
3102 pushValue(I.getOperand(1), InstID, Vals);
3103 Vals.push_back(cast<CmpInst>(I).getPredicate());
3105 if (Flags != 0)
3106 Vals.push_back(Flags);
3107 break;
3108 }
3109
3110 case Instruction::Ret:
3111 {
3113 unsigned NumOperands = I.getNumOperands();
3114 if (NumOperands == 0)
3115 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3116 else if (NumOperands == 1) {
3117 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3118 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3119 } else {
3120 for (const Value *Op : I.operands())
3121 pushValueAndType(Op, InstID, Vals);
3122 }
3123 }
3124 break;
3125 case Instruction::Br:
3126 {
3128 const BranchInst &II = cast<BranchInst>(I);
3129 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3130 if (II.isConditional()) {
3131 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
3132 pushValue(II.getCondition(), InstID, Vals);
3133 }
3134 }
3135 break;
3136 case Instruction::Switch:
3137 {
3139 const SwitchInst &SI = cast<SwitchInst>(I);
3140 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
3141 pushValue(SI.getCondition(), InstID, Vals);
3142 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
3143 for (auto Case : SI.cases()) {
3144 Vals.push_back(VE.getValueID(Case.getCaseValue()));
3145 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
3146 }
3147 }
3148 break;
3149 case Instruction::IndirectBr:
3151 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3152 // Encode the address operand as relative, but not the basic blocks.
3153 pushValue(I.getOperand(0), InstID, Vals);
3154 for (const Value *Op : drop_begin(I.operands()))
3155 Vals.push_back(VE.getValueID(Op));
3156 break;
3157
3158 case Instruction::Invoke: {
3159 const InvokeInst *II = cast<InvokeInst>(&I);
3160 const Value *Callee = II->getCalledOperand();
3161 FunctionType *FTy = II->getFunctionType();
3162
3163 if (II->hasOperandBundles())
3164 writeOperandBundles(*II, InstID);
3165
3167
3168 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
3169 Vals.push_back(II->getCallingConv() | 1 << 13);
3170 Vals.push_back(VE.getValueID(II->getNormalDest()));
3171 Vals.push_back(VE.getValueID(II->getUnwindDest()));
3172 Vals.push_back(VE.getTypeID(FTy));
3173 pushValueAndType(Callee, InstID, Vals);
3174
3175 // Emit value #'s for the fixed parameters.
3176 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3177 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3178
3179 // Emit type/value pairs for varargs params.
3180 if (FTy->isVarArg()) {
3181 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
3182 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3183 }
3184 break;
3185 }
3186 case Instruction::Resume:
3188 pushValueAndType(I.getOperand(0), InstID, Vals);
3189 break;
3190 case Instruction::CleanupRet: {
3192 const auto &CRI = cast<CleanupReturnInst>(I);
3193 pushValue(CRI.getCleanupPad(), InstID, Vals);
3194 if (CRI.hasUnwindDest())
3195 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
3196 break;
3197 }
3198 case Instruction::CatchRet: {
3200 const auto &CRI = cast<CatchReturnInst>(I);
3201 pushValue(CRI.getCatchPad(), InstID, Vals);
3202 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
3203 break;
3204 }
3205 case Instruction::CleanupPad:
3206 case Instruction::CatchPad: {
3207 const auto &FuncletPad = cast<FuncletPadInst>(I);
3208 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
3210 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3211
3212 unsigned NumArgOperands = FuncletPad.arg_size();
3213 Vals.push_back(NumArgOperands);
3214 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
3215 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
3216 break;
3217 }
3218 case Instruction::CatchSwitch: {
3220 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
3221
3222 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3223
3224 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3225 Vals.push_back(NumHandlers);
3226 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3227 Vals.push_back(VE.getValueID(CatchPadBB));
3228
3229 if (CatchSwitch.hasUnwindDest())
3230 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3231 break;
3232 }
3233 case Instruction::CallBr: {
3234 const CallBrInst *CBI = cast<CallBrInst>(&I);
3235 const Value *Callee = CBI->getCalledOperand();
3236 FunctionType *FTy = CBI->getFunctionType();
3237
3238 if (CBI->hasOperandBundles())
3239 writeOperandBundles(*CBI, InstID);
3240
3242
3244
3247
3248 Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3249 Vals.push_back(CBI->getNumIndirectDests());
3250 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3251 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3252
3253 Vals.push_back(VE.getTypeID(FTy));
3254 pushValueAndType(Callee, InstID, Vals);
3255
3256 // Emit value #'s for the fixed parameters.
3257 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3258 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3259
3260 // Emit type/value pairs for varargs params.
3261 if (FTy->isVarArg()) {
3262 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3263 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3264 }
3265 break;
3266 }
3267 case Instruction::Unreachable:
3269 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3270 break;
3271
3272 case Instruction::PHI: {
3273 const PHINode &PN = cast<PHINode>(I);
3275 // With the newer instruction encoding, forward references could give
3276 // negative valued IDs. This is most common for PHIs, so we use
3277 // signed VBRs.
3279 Vals64.push_back(VE.getTypeID(PN.getType()));
3280 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3281 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3282 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3283 }
3284
3286 if (Flags != 0)
3287 Vals64.push_back(Flags);
3288
3289 // Emit a Vals64 vector and exit.
3290 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3291 Vals64.clear();
3292 return;
3293 }
3294
3295 case Instruction::LandingPad: {
3296 const LandingPadInst &LP = cast<LandingPadInst>(I);
3298 Vals.push_back(VE.getTypeID(LP.getType()));
3299 Vals.push_back(LP.isCleanup());
3300 Vals.push_back(LP.getNumClauses());
3301 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3302 if (LP.isCatch(I))
3304 else
3306 pushValueAndType(LP.getClause(I), InstID, Vals);
3307 }
3308 break;
3309 }
3310
3311 case Instruction::Alloca: {
3313 const AllocaInst &AI = cast<AllocaInst>(I);
3314 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3315 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3316 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3317 using APV = AllocaPackedValues;
3318 unsigned Record = 0;
3319 unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3320 Bitfield::set<APV::AlignLower>(
3321 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3322 Bitfield::set<APV::AlignUpper>(Record,
3323 EncodedAlign >> APV::AlignLower::Bits);
3324 Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3325 Bitfield::set<APV::ExplicitType>(Record, true);
3326 Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3327 Vals.push_back(Record);
3328
3329 unsigned AS = AI.getAddressSpace();
3330 if (AS != M.getDataLayout().getAllocaAddrSpace())
3331 Vals.push_back(AS);
3332 break;
3333 }
3334
3335 case Instruction::Load:
3336 if (cast<LoadInst>(I).isAtomic()) {
3338 pushValueAndType(I.getOperand(0), InstID, Vals);
3339 } else {
3341 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3342 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3343 }
3344 Vals.push_back(VE.getTypeID(I.getType()));
3345 Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3346 Vals.push_back(cast<LoadInst>(I).isVolatile());
3347 if (cast<LoadInst>(I).isAtomic()) {
3348 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3349 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3350 }
3351 break;
3352 case Instruction::Store:
3353 if (cast<StoreInst>(I).isAtomic())
3355 else
3357 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
3358 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3359 Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3360 Vals.push_back(cast<StoreInst>(I).isVolatile());
3361 if (cast<StoreInst>(I).isAtomic()) {
3362 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3363 Vals.push_back(
3364 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3365 }
3366 break;
3367 case Instruction::AtomicCmpXchg:
3369 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3370 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3371 pushValue(I.getOperand(2), InstID, Vals); // newval.
3372 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3373 Vals.push_back(
3374 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3375 Vals.push_back(
3376 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3377 Vals.push_back(
3378 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3379 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3380 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3381 break;
3382 case Instruction::AtomicRMW:
3384 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3385 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3386 Vals.push_back(
3387 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
3388 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3389 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3390 Vals.push_back(
3391 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3392 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3393 break;
3394 case Instruction::Fence:
3396 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3397 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3398 break;
3399 case Instruction::Call: {
3400 const CallInst &CI = cast<CallInst>(I);
3401 FunctionType *FTy = CI.getFunctionType();
3402
3403 if (CI.hasOperandBundles())
3404 writeOperandBundles(CI, InstID);
3405
3407
3409
3410 unsigned Flags = getOptimizationFlags(&I);
3412 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3413 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3415 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3416 unsigned(Flags != 0) << bitc::CALL_FMF);
3417 if (Flags != 0)
3418 Vals.push_back(Flags);
3419
3420 Vals.push_back(VE.getTypeID(FTy));
3421 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3422
3423 // Emit value #'s for the fixed parameters.
3424 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3425 // Check for labels (can happen with asm labels).
3426 if (FTy->getParamType(i)->isLabelTy())
3427 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
3428 else
3429 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3430 }
3431
3432 // Emit type/value pairs for varargs params.
3433 if (FTy->isVarArg()) {
3434 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3435 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3436 }
3437 break;
3438 }
3439 case Instruction::VAArg:
3441 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3442 pushValue(I.getOperand(0), InstID, Vals); // valist.
3443 Vals.push_back(VE.getTypeID(I.getType())); // restype.
3444 break;
3445 case Instruction::Freeze:
3447 pushValueAndType(I.getOperand(0), InstID, Vals);
3448 break;
3449 }
3450
3451 Stream.EmitRecord(Code, Vals, AbbrevToUse);
3452 Vals.clear();
3453}
3454
3455/// Write a GlobalValue VST to the module. The purpose of this data structure is
3456/// to allow clients to efficiently find the function body.
3457void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3458 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3459 // Get the offset of the VST we are writing, and backpatch it into
3460 // the VST forward declaration record.
3461 uint64_t VSTOffset = Stream.GetCurrentBitNo();
3462 // The BitcodeStartBit was the stream offset of the identification block.
3463 VSTOffset -= bitcodeStartBit();
3464 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3465 // Note that we add 1 here because the offset is relative to one word
3466 // before the start of the identification block, which was historically
3467 // always the start of the regular bitcode header.
3468 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3469
3471
3472 auto Abbv = std::make_shared<BitCodeAbbrev>();
3474 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3475 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3476 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3477
3478 for (const Function &F : M) {
3479 uint64_t Record[2];
3480
3481 if (F.isDeclaration())
3482 continue;
3483
3484 Record[0] = VE.getValueID(&F);
3485
3486 // Save the word offset of the function (from the start of the
3487 // actual bitcode written to the stream).
3488 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3489 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3490 // Note that we add 1 here because the offset is relative to one word
3491 // before the start of the identification block, which was historically
3492 // always the start of the regular bitcode header.
3493 Record[1] = BitcodeIndex / 32 + 1;
3494
3495 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3496 }
3497
3498 Stream.ExitBlock();
3499}
3500
3501/// Emit names for arguments, instructions and basic blocks in a function.
3502void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3503 const ValueSymbolTable &VST) {
3504 if (VST.empty())
3505 return;
3506
3508
3509 // FIXME: Set up the abbrev, we know how many values there are!
3510 // FIXME: We know if the type names can use 7-bit ascii.
3512
3513 for (const ValueName &Name : VST) {
3514 // Figure out the encoding to use for the name.
3516
3517 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3518 NameVals.push_back(VE.getValueID(Name.getValue()));
3519
3520 // VST_CODE_ENTRY: [valueid, namechar x N]
3521 // VST_CODE_BBENTRY: [bbid, namechar x N]
3522 unsigned Code;
3523 if (isa<BasicBlock>(Name.getValue())) {
3525 if (Bits == SE_Char6)
3526 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3527 } else {
3529 if (Bits == SE_Char6)
3530 AbbrevToUse = VST_ENTRY_6_ABBREV;
3531 else if (Bits == SE_Fixed7)
3532 AbbrevToUse = VST_ENTRY_7_ABBREV;
3533 }
3534
3535 for (const auto P : Name.getKey())
3536 NameVals.push_back((unsigned char)P);
3537
3538 // Emit the finished record.
3539 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3540 NameVals.clear();
3541 }
3542
3543 Stream.ExitBlock();
3544}
3545
3546void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3547 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3548 unsigned Code;
3549 if (isa<BasicBlock>(Order.V))
3551 else
3553
3554 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3555 Record.push_back(VE.getValueID(Order.V));
3556 Stream.EmitRecord(Code, Record);
3557}
3558
3559void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3561 "Expected to be preserving use-list order");
3562
3563 auto hasMore = [&]() {
3564 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3565 };
3566 if (!hasMore())
3567 // Nothing to do.
3568 return;
3569
3571 while (hasMore()) {
3572 writeUseList(std::move(VE.UseListOrders.back()));
3573 VE.UseListOrders.pop_back();
3574 }
3575 Stream.ExitBlock();
3576}
3577
3578/// Emit a function body to the module stream.
3579void ModuleBitcodeWriter::writeFunction(
3580 const Function &F,
3581 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3582 // Save the bitcode index of the start of this function block for recording
3583 // in the VST.
3584 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3585
3588
3590
3591 // Emit the number of basic blocks, so the reader can create them ahead of
3592 // time.
3593 Vals.push_back(VE.getBasicBlocks().size());
3595 Vals.clear();
3596
3597 // If there are function-local constants, emit them now.
3598 unsigned CstStart, CstEnd;
3599 VE.getFunctionConstantRange(CstStart, CstEnd);
3600 writeConstants(CstStart, CstEnd, false);
3601
3602 // If there is function-local metadata, emit it now.
3603 writeFunctionMetadata(F);
3604
3605 // Keep a running idea of what the instruction ID is.
3606 unsigned InstID = CstEnd;
3607
3608 bool NeedsMetadataAttachment = F.hasMetadata();
3609
3610 DILocation *LastDL = nullptr;
3611 SmallSetVector<Function *, 4> BlockAddressUsers;
3612
3613 // Finally, emit all the instructions, in order.
3614 for (const BasicBlock &BB : F) {
3615 for (const Instruction &I : BB) {
3616 writeInstruction(I, InstID, Vals);
3617
3618 if (!I.getType()->isVoidTy())
3619 ++InstID;
3620
3621 // If the instruction has metadata, write a metadata attachment later.
3622 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3623
3624 // If the instruction has a debug location, emit it.
3625 if (DILocation *DL = I.getDebugLoc()) {
3626 if (DL == LastDL) {
3627 // Just repeat the same debug loc as last time.
3629 } else {
3630 Vals.push_back(DL->getLine());
3631 Vals.push_back(DL->getColumn());
3632 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3633 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3634 Vals.push_back(DL->isImplicitCode());
3636 Vals.clear();
3637 LastDL = DL;
3638 }
3639 }
3640
3641 // If the instruction has DbgRecords attached to it, emit them. Note that
3642 // they come after the instruction so that it's easy to attach them again
3643 // when reading the bitcode, even though conceptually the debug locations
3644 // start "before" the instruction.
3645 if (I.hasDbgRecords() && WriteNewDbgInfoFormatToBitcode) {
3646 /// Try to push the value only (unwrapped), otherwise push the
3647 /// metadata wrapped value. Returns true if the value was pushed
3648 /// without the ValueAsMetadata wrapper.
3649 auto PushValueOrMetadata = [&Vals, InstID,
3650 this](Metadata *RawLocation) {
3651 assert(RawLocation &&
3652 "RawLocation unexpectedly null in DbgVariableRecord");
3653 if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) {
3654 SmallVector<unsigned, 2> ValAndType;
3655 // If the value is a fwd-ref the type is also pushed. We don't
3656 // want the type, so fwd-refs are kept wrapped (pushValueAndType
3657 // returns false if the value is pushed without type).
3658 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
3659 Vals.push_back(ValAndType[0]);
3660 return true;
3661 }
3662 }
3663 // The metadata is a DIArgList, or ValueAsMetadata wrapping a
3664 // fwd-ref. Push the metadata ID.
3665 Vals.push_back(VE.getMetadataID(RawLocation));
3666 return false;
3667 };
3668
3669 // Write out non-instruction debug information attached to this
3670 // instruction. Write it after the instruction so that it's easy to
3671 // re-attach to the instruction reading the records in.
3672 for (DbgRecord &DR : I.DebugMarker->getDbgRecordRange()) {
3673 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
3674 Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc()));
3675 Vals.push_back(VE.getMetadataID(DLR->getLabel()));
3677 Vals.clear();
3678 continue;
3679 }
3680
3681 // First 3 fields are common to all kinds:
3682 // DILocation, DILocalVariable, DIExpression
3683 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
3684 // ..., LocationMetadata
3685 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
3686 // ..., Value
3687 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
3688 // ..., LocationMetadata
3689 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
3690 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
3691 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
3692 Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc()));
3693 Vals.push_back(VE.getMetadataID(DVR.getVariable()));
3694 Vals.push_back(VE.getMetadataID(DVR.getExpression()));
3695 if (DVR.isDbgValue()) {
3696 if (PushValueOrMetadata(DVR.getRawLocation()))
3698 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
3699 else
3701 } else if (DVR.isDbgDeclare()) {
3702 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3704 } else {
3705 assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind");
3706 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3707 Vals.push_back(VE.getMetadataID(DVR.getAssignID()));
3709 Vals.push_back(VE.getMetadataID(DVR.getRawAddress()));
3711 }
3712 Vals.clear();
3713 }
3714 }
3715 }
3716
3717 if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
3718 SmallVector<Value *> Worklist{BA};
3719 SmallPtrSet<Value *, 8> Visited{BA};
3720 while (!Worklist.empty()) {
3721 Value *V = Worklist.pop_back_val();
3722 for (User *U : V->users()) {
3723 if (auto *I = dyn_cast<Instruction>(U)) {
3724 Function *P = I->getFunction();
3725 if (P != &F)
3726 BlockAddressUsers.insert(P);
3727 } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
3728 Visited.insert(U).second)
3729 Worklist.push_back(U);
3730 }
3731 }
3732 }
3733 }
3734
3735 if (!BlockAddressUsers.empty()) {
3736 Vals.resize(BlockAddressUsers.size());
3737 for (auto I : llvm::enumerate(BlockAddressUsers))
3738 Vals[I.index()] = VE.getValueID(I.value());
3740 Vals.clear();
3741 }
3742
3743 // Emit names for all the instructions etc.
3744 if (auto *Symtab = F.getValueSymbolTable())
3745 writeFunctionLevelValueSymbolTable(*Symtab);
3746
3747 if (NeedsMetadataAttachment)
3748 writeFunctionMetadataAttachment(F);
3750 writeUseListBlock(&F);
3751 VE.purgeFunction();
3752 Stream.ExitBlock();
3753}
3754
3755// Emit blockinfo, which defines the standard abbreviations etc.
3756void ModuleBitcodeWriter::writeBlockInfo() {
3757 // We only want to emit block info records for blocks that have multiple
3758 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3759 // Other blocks can define their abbrevs inline.
3760 Stream.EnterBlockInfoBlock();
3761
3762 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3763 auto Abbv = std::make_shared<BitCodeAbbrev>();
3769 VST_ENTRY_8_ABBREV)
3770 llvm_unreachable("Unexpected abbrev ordering!");
3771 }
3772
3773 { // 7-bit fixed width VST_CODE_ENTRY strings.
3774 auto Abbv = std::make_shared<BitCodeAbbrev>();
3780 VST_ENTRY_7_ABBREV)
3781 llvm_unreachable("Unexpected abbrev ordering!");
3782 }
3783 { // 6-bit char6 VST_CODE_ENTRY strings.
3784 auto Abbv = std::make_shared<BitCodeAbbrev>();
3790 VST_ENTRY_6_ABBREV)
3791 llvm_unreachable("Unexpected abbrev ordering!");
3792 }
3793 { // 6-bit char6 VST_CODE_BBENTRY strings.
3794 auto Abbv = std::make_shared<BitCodeAbbrev>();
3800 VST_BBENTRY_6_ABBREV)
3801 llvm_unreachable("Unexpected abbrev ordering!");
3802 }
3803
3804 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3805 auto Abbv = std::make_shared<BitCodeAbbrev>();
3810 CONSTANTS_SETTYPE_ABBREV)
3811 llvm_unreachable("Unexpected abbrev ordering!");
3812 }
3813
3814 { // INTEGER abbrev for CONSTANTS_BLOCK.
3815 auto Abbv = std::make_shared<BitCodeAbbrev>();
3819 CONSTANTS_INTEGER_ABBREV)
3820 llvm_unreachable("Unexpected abbrev ordering!");
3821 }
3822
3823 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3824 auto Abbv = std::make_shared<BitCodeAbbrev>();
3826 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3827 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3829 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3830
3832 CONSTANTS_CE_CAST_Abbrev)
3833 llvm_unreachable("Unexpected abbrev ordering!");
3834 }
3835 { // NULL abbrev for CONSTANTS_BLOCK.
3836 auto Abbv = std::make_shared<BitCodeAbbrev>();
3839 CONSTANTS_NULL_Abbrev)
3840 llvm_unreachable("Unexpected abbrev ordering!");
3841 }
3842
3843 // FIXME: This should only use space for first class types!
3844
3845 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3846 auto Abbv = std::make_shared<BitCodeAbbrev>();
3848 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3849 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3851 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3852 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3853 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3854 FUNCTION_INST_LOAD_ABBREV)
3855 llvm_unreachable("Unexpected abbrev ordering!");
3856 }
3857 { // INST_UNOP abbrev for FUNCTION_BLOCK.
3858 auto Abbv = std::make_shared<BitCodeAbbrev>();
3860 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3861 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3862 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3863 FUNCTION_INST_UNOP_ABBREV)
3864 llvm_unreachable("Unexpected abbrev ordering!");
3865 }
3866 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3867 auto Abbv = std::make_shared<BitCodeAbbrev>();
3869 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3870 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3871 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3872 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3873 FUNCTION_INST_UNOP_FLAGS_ABBREV)
3874 llvm_unreachable("Unexpected abbrev ordering!");
3875 }
3876 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3877 auto Abbv = std::make_shared<BitCodeAbbrev>();
3879 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3880 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3881 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3882 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3883 FUNCTION_INST_BINOP_ABBREV)
3884 llvm_unreachable("Unexpected abbrev ordering!");
3885 }
3886 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3887 auto Abbv = std::make_shared<BitCodeAbbrev>();
3889 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3890 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3891 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3892 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3893 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3894 FUNCTION_INST_BINOP_FLAGS_ABBREV)
3895 llvm_unreachable("Unexpected abbrev ordering!");
3896 }
3897 { // INST_CAST abbrev for FUNCTION_BLOCK.
3898 auto Abbv = std::make_shared<BitCodeAbbrev>();
3900 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3901 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3903 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3904 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3905 FUNCTION_INST_CAST_ABBREV)
3906 llvm_unreachable("Unexpected abbrev ordering!");
3907 }
3908 { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
3909 auto Abbv = std::make_shared<BitCodeAbbrev>();
3911 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3912 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3914 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3915 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3916 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3917 FUNCTION_INST_CAST_FLAGS_ABBREV)
3918 llvm_unreachable("Unexpected abbrev ordering!");
3919 }
3920
3921 { // INST_RET abbrev for FUNCTION_BLOCK.
3922 auto Abbv = std::make_shared<BitCodeAbbrev>();
3924 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3925 FUNCTION_INST_RET_VOID_ABBREV)
3926 llvm_unreachable("Unexpected abbrev ordering!");
3927 }
3928 { // INST_RET abbrev for FUNCTION_BLOCK.
3929 auto Abbv = std::make_shared<BitCodeAbbrev>();
3931 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3932 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3933 FUNCTION_INST_RET_VAL_ABBREV)
3934 llvm_unreachable("Unexpected abbrev ordering!");
3935 }
3936 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3937 auto Abbv = std::make_shared<BitCodeAbbrev>();
3939 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3940 FUNCTION_INST_UNREACHABLE_ABBREV)
3941 llvm_unreachable("Unexpected abbrev ordering!");
3942 }
3943 {
3944 auto Abbv = std::make_shared<BitCodeAbbrev>();
3947 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3948 Log2_32_Ceil(VE.getTypes().size() + 1)));
3951 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3952 FUNCTION_INST_GEP_ABBREV)
3953 llvm_unreachable("Unexpected abbrev ordering!");
3954 }
3955 {
3956 auto Abbv = std::make_shared<BitCodeAbbrev>();
3958 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc
3959 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var
3960 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr
3961 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // val
3962 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3963 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
3964 llvm_unreachable("Unexpected abbrev ordering! 1");
3965 }
3966 Stream.ExitBlock();
3967}
3968
3969/// Write the module path strings, currently only used when generating
3970/// a combined index file.
3971void IndexBitcodeWriter::writeModStrings() {
3973
3974 // TODO: See which abbrev sizes we actually need to emit
3975
3976 // 8-bit fixed-width MST_ENTRY strings.
3977 auto Abbv = std::make_shared<BitCodeAbbrev>();
3982 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3983
3984 // 7-bit fixed width MST_ENTRY strings.
3985 Abbv = std::make_shared<BitCodeAbbrev>();
3990 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3991
3992 // 6-bit char6 MST_ENTRY strings.
3993 Abbv = std::make_shared<BitCodeAbbrev>();
3998 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3999
4000 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
4001 Abbv = std::make_shared<BitCodeAbbrev>();
4008 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
4009
4011 forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
4012 StringRef Key = MPSE.getKey();
4013 const auto &Hash = MPSE.getValue();
4015 unsigned AbbrevToUse = Abbrev8Bit;
4016 if (Bits == SE_Char6)
4017 AbbrevToUse = Abbrev6Bit;
4018 else if (Bits == SE_Fixed7)
4019 AbbrevToUse = Abbrev7Bit;
4020
4021 auto ModuleId = ModuleIdMap.size();
4022 ModuleIdMap[Key] = ModuleId;
4023 Vals.push_back(ModuleId);
4024 Vals.append(Key.begin(), Key.end());
4025
4026 // Emit the finished record.
4027 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
4028
4029 // Emit an optional hash for the module now
4030 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
4031 Vals.assign(Hash.begin(), Hash.end());
4032 // Emit the hash record.
4033 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
4034 }
4035
4036 Vals.clear();
4037 });
4038 Stream.ExitBlock();
4039}
4040
4041/// Write the function type metadata related records that need to appear before
4042/// a function summary entry (whether per-module or combined).
4043template <typename Fn>
4045 FunctionSummary *FS,
4046 Fn GetValueID) {
4047 if (!FS->type_tests().empty())
4048 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
4049
4051
4052 auto WriteVFuncIdVec = [&](uint64_t Ty,
4054 if (VFs.empty())
4055 return;
4056 Record.clear();
4057 for (auto &VF : VFs) {
4058 Record.push_back(VF.GUID);
4059 Record.push_back(VF.Offset);
4060 }
4061 Stream.EmitRecord(Ty, Record);
4062 };
4063
4064 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
4065 FS->type_test_assume_vcalls());
4066 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
4067 FS->type_checked_load_vcalls());
4068
4069 auto WriteConstVCallVec = [&](uint64_t Ty,
4071 for (auto &VC : VCs) {
4072 Record.clear();
4073 Record.push_back(VC.VFunc.GUID);
4074 Record.push_back(VC.VFunc.Offset);
4075 llvm::append_range(Record, VC.Args);
4076 Stream.EmitRecord(Ty, Record);
4077 }
4078 };
4079
4080 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
4081 FS->type_test_assume_const_vcalls());
4082 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
4083 FS->type_checked_load_const_vcalls());
4084
4085 auto WriteRange = [&](ConstantRange Range) {
4087 assert(Range.getLower().getNumWords() == 1);
4088 assert(Range.getUpper().getNumWords() == 1);
4091 };
4092
4093 if (!FS->paramAccesses().empty()) {
4094 Record.clear();
4095 for (auto &Arg : FS->paramAccesses()) {
4096 size_t UndoSize = Record.size();
4097 Record.push_back(Arg.ParamNo);
4098 WriteRange(Arg.Use);
4099 Record.push_back(Arg.Calls.size());
4100 for (auto &Call : Arg.Calls) {
4101 Record.push_back(Call.ParamNo);
4102 std::optional<unsigned> ValueID = GetValueID(Call.Callee);
4103 if (!ValueID) {
4104 // If ValueID is unknown we can't drop just this call, we must drop
4105 // entire parameter.
4106 Record.resize(UndoSize);
4107 break;
4108 }
4109 Record.push_back(*ValueID);
4110 WriteRange(Call.Offsets);
4111 }
4112 }
4113 if (!Record.empty())
4115 }
4116}
4117
4118/// Collect type IDs from type tests used by function.
4119static void
4121 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4122 if (!FS->type_tests().empty())
4123 for (auto &TT : FS->type_tests())
4124 ReferencedTypeIds.insert(TT);
4125
4126 auto GetReferencedTypesFromVFuncIdVec =
4128 for (auto &VF : VFs)
4129 ReferencedTypeIds.insert(VF.GUID);
4130 };
4131
4132 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4133 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4134
4135 auto GetReferencedTypesFromConstVCallVec =
4137 for (auto &VC : VCs)
4138 ReferencedTypeIds.insert(VC.VFunc.GUID);
4139 };
4140
4141 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4142 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4143}
4144
4146 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
4148 NameVals.push_back(args.size());
4149 llvm::append_range(NameVals, args);
4150
4151 NameVals.push_back(ByArg.TheKind);
4152 NameVals.push_back(ByArg.Info);
4153 NameVals.push_back(ByArg.Byte);
4154 NameVals.push_back(ByArg.Bit);
4155}
4156
4158 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4159 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
4160 NameVals.push_back(Id);
4161
4162 NameVals.push_back(Wpd.TheKind);
4163 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
4164 NameVals.push_back(Wpd.SingleImplName.size());
4165
4166 NameVals.push_back(Wpd.ResByArg.size());
4167 for (auto &A : Wpd.ResByArg)
4168 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
4169}
4170
4172 StringTableBuilder &StrtabBuilder,
4173 StringRef Id,
4174 const TypeIdSummary &Summary) {
4175 NameVals.push_back(StrtabBuilder.add(Id));
4176 NameVals.push_back(Id.size());
4177
4178 NameVals.push_back(Summary.TTRes.TheKind);
4179 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
4180 NameVals.push_back(Summary.TTRes.AlignLog2);
4181 NameVals.push_back(Summary.TTRes.SizeM1);
4182 NameVals.push_back(Summary.TTRes.BitMask);
4183 NameVals.push_back(Summary.TTRes.InlineBits);
4184
4185 for (auto &W : Summary.WPDRes)
4186 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
4187 W.second);
4188}
4189
4191 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4192 StringRef Id, const TypeIdCompatibleVtableInfo &Summary,
4193 ValueEnumerator &VE) {
4194 NameVals.push_back(StrtabBuilder.add(Id));
4195 NameVals.push_back(Id.size());
4196
4197 for (auto &P : Summary) {
4198 NameVals.push_back(P.AddressPointOffset);
4199 NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
4200 }
4201}
4202
4203// Adds the allocation contexts to the CallStacks map. We simply use the
4204// size at the time the context was added as the CallStackId. This works because
4205// when we look up the call stacks later on we process the function summaries
4206// and their allocation records in the same exact order.
4208 FunctionSummary *FS, std::function<LinearFrameId(unsigned)> GetStackIndex,
4210 // The interfaces in ProfileData/MemProf.h use a type alias for a stack frame
4211 // id offset into the index of the full stack frames. The ModuleSummaryIndex
4212 // currently uses unsigned. Make sure these stay in sync.
4213 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4214 for (auto &AI : FS->allocs()) {
4215 for (auto &MIB : AI.MIBs) {
4216 SmallVector<unsigned> StackIdIndices;
4217 StackIdIndices.reserve(MIB.StackIdIndices.size());
4218 for (auto Id : MIB.StackIdIndices)
4219 StackIdIndices.push_back(GetStackIndex(Id));
4220 // The CallStackId is the size at the time this context was inserted.
4221 CallStacks.insert({CallStacks.size(), StackIdIndices});
4222 }
4223 }
4224}
4225
4226// Build the radix tree from the accumulated CallStacks, write out the resulting
4227// linearized radix tree array, and return the map of call stack positions into
4228// this array for use when writing the allocation records. The returned map is
4229// indexed by a CallStackId which in this case is implicitly determined by the
4230// order of function summaries and their allocation infos being written.
4233 BitstreamWriter &Stream, unsigned RadixAbbrev) {
4234 assert(!CallStacks.empty());
4235 DenseMap<unsigned, FrameStat> FrameHistogram =
4238 // We don't need a MemProfFrameIndexes map as we have already converted the
4239 // full stack id hash to a linear offset into the StackIds array.
4240 Builder.build(std::move(CallStacks), /*MemProfFrameIndexes=*/nullptr,
4241 FrameHistogram);
4243 RadixAbbrev);
4244 return Builder.takeCallStackPos();
4245}
4246
4248 BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
4249 unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule,
4250 std::function<unsigned(const ValueInfo &VI)> GetValueID,
4251 std::function<unsigned(unsigned)> GetStackIndex,
4252 bool WriteContextSizeInfoIndex,
4254 CallStackId &CallStackCount) {
4256
4257 for (auto &CI : FS->callsites()) {
4258 Record.clear();
4259 // Per module callsite clones should always have a single entry of
4260 // value 0.
4261 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4262 Record.push_back(GetValueID(CI.Callee));
4263 if (!PerModule) {
4264 Record.push_back(CI.StackIdIndices.size());
4265 Record.push_back(CI.Clones.size());
4266 }
4267 for (auto Id : CI.StackIdIndices)
4268 Record.push_back(GetStackIndex(Id));
4269 if (!PerModule) {
4270 for (auto V : CI.Clones)
4271 Record.push_back(V);
4272 }
4275 Record, CallsiteAbbrev);
4276 }
4277
4278 for (auto &AI : FS->allocs()) {
4279 Record.clear();
4280 // Per module alloc versions should always have a single entry of
4281 // value 0.
4282 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4283 Record.push_back(AI.MIBs.size());
4284 if (!PerModule)
4285 Record.push_back(AI.Versions.size());
4286 for (auto &MIB : AI.MIBs) {
4287 Record.push_back((uint8_t)MIB.AllocType);
4288 // Record the index into the radix tree array for this context.
4289 assert(CallStackCount <= CallStackPos.size());
4290 Record.push_back(CallStackPos[CallStackCount++]);
4291 }
4292 if (!PerModule) {
4293 for (auto V : AI.Versions)
4294 Record.push_back(V);
4295 }
4296 assert(AI.ContextSizeInfos.empty() ||
4297 AI.ContextSizeInfos.size() == AI.MIBs.size());
4298 // Optionally emit the context size information if it exists.
4299 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4300 // The abbreviation id for the context ids record should have been created
4301 // if we are emitting the per-module index, which is where we write this
4302 // info.
4303 assert(ContextIdAbbvId);
4304 SmallVector<uint32_t> ContextIds;
4305 // At least one context id per ContextSizeInfos entry (MIB), broken into 2
4306 // halves.
4307 ContextIds.reserve(AI.ContextSizeInfos.size() * 2);
4308 for (auto &Infos : AI.ContextSizeInfos) {
4309 Record.push_back(Infos.size());
4310 for (auto [FullStackId, TotalSize] : Infos) {
4311 // The context ids are emitted separately as a fixed width array,
4312 // which is more efficient than a VBR given that these hashes are
4313 // typically close to 64-bits. The max fixed width entry is 32 bits so
4314 // it is split into 2.
4315 ContextIds.push_back(static_cast<uint32_t>(FullStackId >> 32));
4316 ContextIds.push_back(static_cast<uint32_t>(FullStackId));
4317 Record.push_back(TotalSize);
4318 }
4319 }
4320 // The context ids are expected by the reader to immediately precede the
4321 // associated alloc info record.
4322 Stream.EmitRecord(bitc::FS_ALLOC_CONTEXT_IDS, ContextIds,
4323 ContextIdAbbvId);
4324 }
4325 Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_ALLOC_INFO
4327 Record, AllocAbbrev);
4328 }
4329}
4330
4331// Helper to emit a single function summary record.
4332void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4334 unsigned ValueID, unsigned FSCallsRelBFAbbrev,
4335 unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
4336 unsigned AllocAbbrev, unsigned ContextIdAbbvId, const Function &F,
4338 CallStackId &CallStackCount) {
4339 NameVals.push_back(ValueID);
4340
4341 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4342
4344 Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
4345 return {VE.getValueID(VI.getValue())};
4346 });
4347
4349 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4350 /*PerModule*/ true,
4351 /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
4352 /*GetStackIndex*/ [&](unsigned I) { return I; },
4353 /*WriteContextSizeInfoIndex*/ true, CallStackPos, CallStackCount);
4354
4355 auto SpecialRefCnts = FS->specialRefCounts();
4356 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4357 NameVals.push_back(FS->instCount());
4358 NameVals.push_back(getEncodedFFlags(FS->fflags()));
4359 NameVals.push_back(FS->refs().size());
4360 NameVals.push_back(SpecialRefCnts.first); // rorefcnt
4361 NameVals.push_back(SpecialRefCnts.second); // worefcnt
4362
4363 for (auto &RI : FS->refs())
4364 NameVals.push_back(getValueId(RI));
4365
4366 const bool UseRelBFRecord =
4367 WriteRelBFToSummary && !F.hasProfileData() &&
4369 for (auto &ECI : FS->calls()) {
4370 NameVals.push_back(getValueId(ECI.first));
4371 if (UseRelBFRecord)
4372 NameVals.push_back(getEncodedRelBFCallEdgeInfo(ECI.second));
4373 else
4374 NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));
4375 }
4376
4377 unsigned FSAbbrev =
4378 (UseRelBFRecord ? FSCallsRelBFAbbrev : FSCallsProfileAbbrev);
4379 unsigned Code =