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 =
4381
4382 // Emit the finished record.
4383 Stream.EmitRecord(Code, NameVals, FSAbbrev);
4384 NameVals.clear();
4385}
4386
4387// Collect the global value references in the given variable's initializer,
4388// and emit them in a summary record.
4389void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4390 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4391 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
4392 auto VI = Index->getValueInfo(V.getGUID());
4393 if (!VI || VI.getSummaryList().empty()) {
4394 // Only declarations should not have a summary (a declaration might however
4395 // have a summary if the def was in module level asm).
4396 assert(V.isDeclaration());
4397 return;
4398 }
4399 auto *Summary = VI.getSummaryList()[0].get();
4400 NameVals.push_back(VE.getValueID(&V));
4401 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
4402 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4403 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4404
4405 auto VTableFuncs = VS->vTableFuncs();
4406 if (!VTableFuncs.empty())
4407 NameVals.push_back(VS->refs().size());
4408
4409 unsigned SizeBeforeRefs = NameVals.size();
4410 for (auto &RI : VS->refs())
4411 NameVals.push_back(VE.getValueID(RI.getValue()));
4412 // Sort the refs for determinism output, the vector returned by FS->refs() has
4413 // been initialized from a DenseSet.
4414 llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
4415
4416 if (VTableFuncs.empty())
4418 FSModRefsAbbrev);
4419 else {
4420 // VTableFuncs pairs should already be sorted by offset.
4421 for (auto &P : VTableFuncs) {
4422 NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
4423 NameVals.push_back(P.VTableOffset);
4424 }
4425
4427 FSModVTableRefsAbbrev);
4428 }
4429 NameVals.clear();
4430}
4431
4432/// Emit the per-module summary section alongside the rest of
4433/// the module's bitcode.
4434void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4435 // By default we compile with ThinLTO if the module has a summary, but the
4436 // client can request full LTO with a module flag.
4437 bool IsThinLTO = true;
4438 if (auto *MD =
4439 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
4440 IsThinLTO = MD->getZExtValue();
4443 4);
4444
4445 Stream.EmitRecord(
4448
4449 // Write the index flags.
4450 uint64_t Flags = 0;
4451 // Bits 1-3 are set only in the combined index, skip them.
4452 if (Index->enableSplitLTOUnit())
4453 Flags |= 0x8;
4454 if (Index->hasUnifiedLTO())
4455 Flags |= 0x200;
4456
4458
4459 if (Index->begin() == Index->end()) {
4460 Stream.ExitBlock();
4461 return;
4462 }
4463
4464 auto Abbv = std::make_shared<BitCodeAbbrev>();
4467 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
4470 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4471
4472 for (const auto &GVI : valueIds()) {
4474 ArrayRef<uint32_t>{GVI.second,
4475 static_cast<uint32_t>(GVI.first >> 32),
4476 static_cast<uint32_t>(GVI.first)},
4477 ValueGuidAbbrev);
4478 }
4479
4480 if (!Index->stackIds().empty()) {
4481 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4482 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4483 // numids x stackid
4484 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4485 // The stack ids are hashes that are close to 64 bits in size, so emitting
4486 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
4487 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4488 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4490 Vals.reserve(Index->stackIds().size() * 2);
4491 for (auto Id : Index->stackIds()) {
4492 Vals.push_back(static_cast<uint32_t>(Id >> 32));
4493 Vals.push_back(static_cast<uint32_t>(Id));
4494 }
4495 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
4496 }
4497
4498 // n x context id
4499 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4500 ContextIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_ALLOC_CONTEXT_IDS));
4501 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4502 // The context ids are hashes that are close to 64 bits in size, so emitting
4503 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
4504 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4505 unsigned ContextIdAbbvId = Stream.EmitAbbrev(std::move(ContextIdAbbv));
4506
4507 // Abbrev for FS_PERMODULE_PROFILE.
4508 Abbv = std::make_shared<BitCodeAbbrev>();
4510 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4511 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags
4512 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4513 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4514 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4515 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4516 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4517 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4520 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4521
4522 // Abbrev for FS_PERMODULE_RELBF.
4523 Abbv = std::make_shared<BitCodeAbbrev>();
4525 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4526 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4527 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4528 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4529 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4530 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4531 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4532 // numrefs x valueid, n x (valueid, rel_block_freq+tailcall])
4535 unsigned FSCallsRelBFAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4536
4537 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4538 Abbv = std::make_shared<BitCodeAbbrev>();
4540 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4541 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4542 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4544 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4545
4546 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4547 Abbv = std::make_shared<BitCodeAbbrev>();
4549 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4550 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4551 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4552 // numrefs x valueid, n x (valueid , offset)
4555 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4556
4557 // Abbrev for FS_ALIAS.
4558 Abbv = std::make_shared<BitCodeAbbrev>();
4559 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4560 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4561 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4562 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4563 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4564
4565 // Abbrev for FS_TYPE_ID_METADATA
4566 Abbv = std::make_shared<BitCodeAbbrev>();
4568 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4569 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4570 // n x (valueid , offset)
4573 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4574
4575 Abbv = std::make_shared<BitCodeAbbrev>();
4577 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4578 // n x stackidindex
4581 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4582
4583 Abbv = std::make_shared<BitCodeAbbrev>();
4585 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
4586 // n x (alloc type, context radix tree index)
4587 // optional: nummib x (numcontext x total size)
4590 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4591
4592 Abbv = std::make_shared<BitCodeAbbrev>();
4594 // n x entry
4597 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4598
4599 // First walk through all the functions and collect the allocation contexts in
4600 // their associated summaries, for use in constructing a radix tree of
4601 // contexts. Note that we need to do this in the same order as the functions
4602 // are processed further below since the call stack positions in the resulting
4603 // radix tree array are identified based on this order.
4605 for (const Function &F : M) {
4606 // Summary emission does not support anonymous functions, they have to be
4607 // renamed using the anonymous function renaming pass.
4608 if (!F.hasName())
4609 report_fatal_error("Unexpected anonymous function when writing summary");
4610
4611 ValueInfo VI = Index->getValueInfo(F.getGUID());
4612 if (!VI || VI.getSummaryList().empty()) {
4613 // Only declarations should not have a summary (a declaration might
4614 // however have a summary if the def was in module level asm).
4615 assert(F.isDeclaration());
4616 continue;
4617 }
4618 auto *Summary = VI.getSummaryList()[0].get();
4619 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4621 FS, /*GetStackIndex*/ [](unsigned I) { return I; }, CallStacks);
4622 }
4623 // Finalize the radix tree, write it out, and get the map of positions in the
4624 // linearized tree array.
4626 if (!CallStacks.empty()) {
4627 CallStackPos =
4628 writeMemoryProfileRadixTree(std::move(CallStacks), Stream, RadixAbbrev);
4629 }
4630
4631 // Keep track of the current index into the CallStackPos map.
4632 CallStackId CallStackCount = 0;
4633
4635 // Iterate over the list of functions instead of the Index to
4636 // ensure the ordering is stable.
4637 for (const Function &F : M) {
4638 // Summary emission does not support anonymous functions, they have to
4639 // renamed using the anonymous function renaming pass.
4640 if (!F.hasName())
4641 report_fatal_error("Unexpected anonymous function when writing summary");
4642
4643 ValueInfo VI = Index->getValueInfo(F.getGUID());
4644 if (!VI || VI.getSummaryList().empty()) {
4645 // Only declarations should not have a summary (a declaration might
4646 // however have a summary if the def was in module level asm).
4647 assert(F.isDeclaration());
4648 continue;
4649 }
4650 auto *Summary = VI.getSummaryList()[0].get();
4651 writePerModuleFunctionSummaryRecord(
4652 NameVals, Summary, VE.getValueID(&F), FSCallsRelBFAbbrev,
4653 FSCallsProfileAbbrev, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId, F,
4654 CallStackPos, CallStackCount);
4655 }
4656
4657 // Capture references from GlobalVariable initializers, which are outside
4658 // of a function scope.
4659 for (const GlobalVariable &G : M.globals())
4660 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4661 FSModVTableRefsAbbrev);
4662
4663 for (const GlobalAlias &A : M.aliases()) {
4664 auto *Aliasee = A.getAliaseeObject();
4665 // Skip ifunc and nameless functions which don't have an entry in the
4666 // summary.
4667 if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
4668 continue;
4669 auto AliasId = VE.getValueID(&A);
4670 auto AliaseeId = VE.getValueID(Aliasee);
4671 NameVals.push_back(AliasId);
4672 auto *Summary = Index->getGlobalValueSummary(A);
4673 AliasSummary *AS = cast<AliasSummary>(Summary);
4674 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4675 NameVals.push_back(AliaseeId);
4676 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4677 NameVals.clear();
4678 }
4679
4680 for (auto &S : Index->typeIdCompatibleVtableMap()) {
4681 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4682 S.second, VE);
4683 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4684 TypeIdCompatibleVtableAbbrev);
4685 NameVals.clear();
4686 }
4687
4688 if (Index->getBlockCount())
4690 ArrayRef<uint64_t>{Index->getBlockCount()});
4691
4692 Stream.ExitBlock();
4693}
4694
4695/// Emit the combined summary section into the combined index file.
4696void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4698 Stream.EmitRecord(
4701
4702 // Write the index flags.
4704
4705 auto Abbv = std::make_shared<BitCodeAbbrev>();
4708 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
4711 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4712
4713 for (const auto &GVI : valueIds()) {
4715 ArrayRef<uint32_t>{GVI.second,
4716 static_cast<uint32_t>(GVI.first >> 32),
4717 static_cast<uint32_t>(GVI.first)},
4718 ValueGuidAbbrev);
4719 }
4720
4721 // Write the stack ids used by this index, which will be a subset of those in
4722 // the full index in the case of distributed indexes.
4723 if (!StackIds.empty()) {
4724 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4725 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4726 // numids x stackid
4727 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4728 // The stack ids are hashes that are close to 64 bits in size, so emitting
4729 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
4730 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4731 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4733 Vals.reserve(StackIds.size() * 2);
4734 for (auto Id : StackIds) {
4735 Vals.push_back(static_cast<uint32_t>(Id >> 32));
4736 Vals.push_back(static_cast<uint32_t>(Id));
4737 }
4738 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
4739 }
4740
4741 // Abbrev for FS_COMBINED_PROFILE.
4742 Abbv = std::make_shared<BitCodeAbbrev>();
4744 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4745 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4746 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4747 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4748 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4749 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
4750 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4751 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4752 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4753 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4756 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4757
4758 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
4759 Abbv = std::make_shared<BitCodeAbbrev>();
4761 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4762 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4763 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4764 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4766 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4767
4768 // Abbrev for FS_COMBINED_ALIAS.
4769 Abbv = std::make_shared<BitCodeAbbrev>();
4771 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4772 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4773 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4774 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4775 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4776
4777 Abbv = std::make_shared<BitCodeAbbrev>();
4779 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4780 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices
4781 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
4782 // numstackindices x stackidindex, numver x version
4785 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4786
4787 Abbv = std::make_shared<BitCodeAbbrev>();
4789 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
4790 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
4791 // nummib x (alloc type, context radix tree index),
4792 // numver x version
4793 // optional: nummib x total size
4796 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4797
4798 Abbv = std::make_shared<BitCodeAbbrev>();
4800 // n x entry
4803 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4804
4805 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) -> bool {
4806 if (DecSummaries == nullptr)
4807 return false;
4808 return DecSummaries->count(GVS);
4809 };
4810
4811 // The aliases are emitted as a post-pass, and will point to the value
4812 // id of the aliasee. Save them in a vector for post-processing.
4814
4815 // Save the value id for each summary for alias emission.
4817
4819
4820 // Set that will be populated during call to writeFunctionTypeMetadataRecords
4821 // with the type ids referenced by this index file.
4822 std::set<GlobalValue::GUID> ReferencedTypeIds;
4823
4824 // For local linkage, we also emit the original name separately
4825 // immediately after the record.
4826 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
4827 // We don't need to emit the original name if we are writing the index for
4828 // distributed backends (in which case ModuleToSummariesForIndex is
4829 // non-null). The original name is only needed during the thin link, since
4830 // for SamplePGO the indirect call targets for local functions have
4831 // have the original name annotated in profile.
4832 // Continue to emit it when writing out the entire combined index, which is
4833 // used in testing the thin link via llvm-lto.
4834 if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
4835 return;
4836 NameVals.push_back(S.getOriginalName());
4838 NameVals.clear();
4839 };
4840
4841 // First walk through all the functions and collect the allocation contexts in
4842 // their associated summaries, for use in constructing a radix tree of
4843 // contexts. Note that we need to do this in the same order as the functions
4844 // are processed further below since the call stack positions in the resulting
4845 // radix tree array are identified based on this order.
4847 forEachSummary([&](GVInfo I, bool IsAliasee) {
4848 GlobalValueSummary *S = I.second;
4849 assert(S);
4850 auto *FS = dyn_cast<FunctionSummary>(S);
4851 if (!FS)
4852 return;
4854 FS,
4855 /*GetStackIndex*/
4856 [&](unsigned I) {
4857 // Get the corresponding index into the list of StackIds actually
4858 // being written for this combined index (which may be a subset in
4859 // the case of distributed indexes).
4860 assert(StackIdIndicesToIndex.contains(I));
4861 return StackIdIndicesToIndex[I];
4862 },
4863 CallStacks);
4864 });
4865 // Finalize the radix tree, write it out, and get the map of positions in the
4866 // linearized tree array.
4868 if (!CallStacks.empty()) {
4869 CallStackPos =
4870 writeMemoryProfileRadixTree(std::move(CallStacks), Stream, RadixAbbrev);
4871 }
4872
4873 // Keep track of the current index into the CallStackPos map.
4874 CallStackId CallStackCount = 0;
4875
4876 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
4877 forEachSummary([&](GVInfo I, bool IsAliasee) {
4878 GlobalValueSummary *S = I.second;
4879 assert(S);
4880 DefOrUseGUIDs.insert(I.first);
4881 for (const ValueInfo &VI : S->refs())
4882 DefOrUseGUIDs.insert(VI.getGUID());
4883
4884 auto ValueId = getValueId(I.first);
4885 assert(ValueId);
4886 SummaryToValueIdMap[S] = *ValueId;
4887
4888 // If this is invoked for an aliasee, we want to record the above
4889 // mapping, but then not emit a summary entry (if the aliasee is
4890 // to be imported, we will invoke this separately with IsAliasee=false).
4891 if (IsAliasee)
4892 return;
4893
4894 if (auto *AS = dyn_cast<AliasSummary>(S)) {
4895 // Will process aliases as a post-pass because the reader wants all
4896 // global to be loaded first.
4897 Aliases.push_back(AS);
4898 return;
4899 }
4900
4901 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
4902 NameVals.push_back(*ValueId);
4903 assert(ModuleIdMap.count(VS->modulePath()));
4904 NameVals.push_back(ModuleIdMap[VS->modulePath()]);
4905 NameVals.push_back(
4906 getEncodedGVSummaryFlags(VS->flags(), shouldImportValueAsDecl(VS)));
4907 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4908 for (auto &RI : VS->refs()) {
4909 auto RefValueId = getValueId(RI.getGUID());
4910 if (!RefValueId)
4911 continue;
4912 NameVals.push_back(*RefValueId);
4913 }
4914
4915 // Emit the finished record.
4917 FSModRefsAbbrev);
4918 NameVals.clear();
4919 MaybeEmitOriginalName(*S);
4920 return;
4921 }
4922
4923 auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> {
4924 if (!VI)
4925 return std::nullopt;
4926 return getValueId(VI.getGUID());
4927 };
4928
4929 auto *FS = cast<FunctionSummary>(S);
4930 writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
4931 getReferencedTypeIds(FS, ReferencedTypeIds);
4932
4934 Stream, FS, CallsiteAbbrev, AllocAbbrev, /*ContextIdAbbvId*/ 0,
4935 /*PerModule*/ false,
4936 /*GetValueId*/
4937 [&](const ValueInfo &VI) -> unsigned {
4938 std::optional<unsigned> ValueID = GetValueId(VI);
4939 // This can happen in shared index files for distributed ThinLTO if
4940 // the callee function summary is not included. Record 0 which we
4941 // will have to deal with conservatively when doing any kind of
4942 // validation in the ThinLTO backends.
4943 if (!ValueID)
4944 return 0;
4945 return *ValueID;
4946 },
4947 /*GetStackIndex*/
4948 [&](unsigned I) {
4949 // Get the corresponding index into the list of StackIds actually
4950 // being written for this combined index (which may be a subset in
4951 // the case of distributed indexes).
4952 assert(StackIdIndicesToIndex.contains(I));
4953 return StackIdIndicesToIndex[I];
4954 },
4955 /*WriteContextSizeInfoIndex*/ false, CallStackPos, CallStackCount);
4956
4957 NameVals.push_back(*ValueId);
4958 assert(ModuleIdMap.count(FS->modulePath()));
4959 NameVals.push_back(ModuleIdMap[FS->modulePath()]);
4960 NameVals.push_back(
4961 getEncodedGVSummaryFlags(FS->flags(), shouldImportValueAsDecl(FS)));
4962 NameVals.push_back(FS->instCount());
4963 NameVals.push_back(getEncodedFFlags(FS->fflags()));
4964 // TODO: Stop writing entry count and bump bitcode version.
4965 NameVals.push_back(0 /* EntryCount */);
4966
4967 // Fill in below
4968 NameVals.push_back(0); // numrefs
4969 NameVals.push_back(0); // rorefcnt
4970 NameVals.push_back(0); // worefcnt
4971
4972 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
4973 for (auto &RI : FS->refs()) {
4974 auto RefValueId = getValueId(RI.getGUID());
4975 if (!RefValueId)
4976 continue;
4977 NameVals.push_back(*RefValueId);
4978 if (RI.isReadOnly())
4979 RORefCnt++;
4980 else if (RI.isWriteOnly())
4981 WORefCnt++;
4982 Count++;
4983 }
4984 NameVals[6] = Count;
4985 NameVals[7] = RORefCnt;
4986 NameVals[8] = WORefCnt;
4987
4988 for (auto &EI : FS->calls()) {
4989 // If this GUID doesn't have a value id, it doesn't have a function
4990 // summary and we don't need to record any calls to it.
4991 std::optional<unsigned> CallValueId = GetValueId(EI.first);
4992 if (!CallValueId)
4993 continue;
4994 NameVals.push_back(*CallValueId);
4995 NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second));
4996 }
4997
4998 // Emit the finished record.
4999 Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals,
5000 FSCallsProfileAbbrev);
5001 NameVals.clear();
5002 MaybeEmitOriginalName(*S);
5003 });
5004
5005 for (auto *AS : Aliases) {
5006 auto AliasValueId = SummaryToValueIdMap[AS];
5007 assert(AliasValueId);
5008 NameVals.push_back(AliasValueId);
5009 assert(ModuleIdMap.count(AS->modulePath()));
5010 NameVals.push_back(ModuleIdMap[AS->modulePath()]);
5011 NameVals.push_back(
5012 getEncodedGVSummaryFlags(AS->flags(), shouldImportValueAsDecl(AS)));
5013 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
5014 assert(AliaseeValueId);
5015 NameVals.push_back(AliaseeValueId);
5016
5017 // Emit the finished record.
5018 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
5019 NameVals.clear();
5020 MaybeEmitOriginalName(*AS);
5021
5022 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
5023 getReferencedTypeIds(FS, ReferencedTypeIds);
5024 }
5025
5026 if (!Index.cfiFunctionDefs().empty()) {
5027 for (auto &S : Index.cfiFunctionDefs()) {
5028 if (DefOrUseGUIDs.contains(
5030 NameVals.push_back(StrtabBuilder.add(S));
5031 NameVals.push_back(S.size());
5032 }
5033 }
5034 if (!NameVals.empty()) {
5035 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
5036 NameVals.clear();
5037 }
5038 }
5039
5040 if (!Index.cfiFunctionDecls().empty()) {
5041 for (auto &S : Index.cfiFunctionDecls()) {
5042 if (DefOrUseGUIDs.contains(
5044 NameVals.push_back(StrtabBuilder.add(S));
5045 NameVals.push_back(S.size());
5046 }
5047 }
5048 if (!NameVals.empty()) {
5049 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
5050 NameVals.clear();
5051 }
5052 }
5053
5054 // Walk the GUIDs that were referenced, and write the
5055 // corresponding type id records.
5056 for (auto &T : ReferencedTypeIds) {
5057 auto TidIter = Index.typeIds().equal_range(T);
5058 for (const auto &[GUID, TypeIdPair] : make_range(TidIter)) {
5059 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, TypeIdPair.first,
5060 TypeIdPair.second);
5061 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
5062 NameVals.clear();
5063 }
5064 }
5065
5066 if (Index.getBlockCount())
5068 ArrayRef<uint64_t>{Index.getBlockCount()});
5069
5070 Stream.ExitBlock();
5071}
5072
5073/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
5074/// current llvm version, and a record for the epoch number.
5077
5078 // Write the "user readable" string identifying the bitcode producer
5079 auto Abbv = std::make_shared<BitCodeAbbrev>();
5083 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5085 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5086
5087 // Write the epoch version
5088 Abbv = std::make_shared<BitCodeAbbrev>();
5091 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5092 constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
5093 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
5094 Stream.ExitBlock();
5095}
5096
5097void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5098 // Emit the module's hash.
5099 // MODULE_CODE_HASH: [5*i32]
5100 if (GenerateHash) {
5101 uint32_t Vals[5];
5102 Hasher.update(ArrayRef<uint8_t>(
5103 reinterpret_cast<const uint8_t *>(View.data()), View.size()));
5104 std::array<uint8_t, 20> Hash = Hasher.result();
5105 for (int Pos = 0; Pos < 20; Pos += 4) {
5106 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
5107 }
5108
5109 // Emit the finished record.
5110 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
5111
5112 if (ModHash)
5113 // Save the written hash value.
5114 llvm::copy(Vals, std::begin(*ModHash));
5115 }
5116}
5117
5118void ModuleBitcodeWriter::write() {
5120
5122 // We will want to write the module hash at this point. Block any flushing so
5123 // we can have access to the whole underlying data later.
5124 Stream.markAndBlockFlushing();
5125
5126 writeModuleVersion();
5127
5128 // Emit blockinfo, which defines the standard abbreviations etc.
5129 writeBlockInfo();
5130
5131 // Emit information describing all of the types in the module.
5132 writeTypeTable();
5133
5134 // Emit information about attribute groups.
5135 writeAttributeGroupTable();
5136
5137 // Emit information about parameter attributes.
5138 writeAttributeTable();
5139
5140 writeComdats();
5141
5142 // Emit top-level description of module, including target triple, inline asm,
5143 // descriptors for global variables, and function prototype info.
5144 writeModuleInfo();
5145
5146 // Emit constants.
5147 writeModuleConstants();
5148
5149 // Emit metadata kind names.
5150 writeModuleMetadataKinds();
5151
5152 // Emit metadata.
5153 writeModuleMetadata();
5154
5155 // Emit module-level use-lists.
5157 writeUseListBlock(nullptr);
5158
5159 writeOperandBundleTags();
5160 writeSyncScopeNames();
5161
5162 // Emit function bodies.
5163 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5164 for (const Function &F : M)
5165 if (!F.isDeclaration())
5166 writeFunction(F, FunctionToBitcodeIndex);
5167
5168 // Need to write after the above call to WriteFunction which populates
5169 // the summary information in the index.
5170 if (Index)
5171 writePerModuleGlobalValueSummary();
5172
5173 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5174
5175 writeModuleHash(Stream.getMarkedBufferAndResumeFlushing());
5176
5177 Stream.ExitBlock();
5178}
5179
5181 uint32_t &Position) {
5182 support::endian::write32le(&Buffer[Position], Value);
5183 Position += 4;
5184}
5185
5186/// If generating a bc file on darwin, we have to emit a
5187/// header and trailer to make it compatible with the system archiver. To do
5188/// this we emit the following header, and then emit a trailer that pads the
5189/// file out to be a multiple of 16 bytes.
5190///
5191/// struct bc_header {
5192/// uint32_t Magic; // 0x0B17C0DE
5193/// uint32_t Version; // Version, currently always 0.
5194/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
5195/// uint32_t BitcodeSize; // Size of traditional bitcode file.
5196/// uint32_t CPUType; // CPU specifier.
5197/// ... potentially more later ...
5198/// };
5200 const Triple &TT) {
5201 unsigned CPUType = ~0U;
5202
5203 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
5204 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
5205 // number from /usr/include/mach/machine.h. It is ok to reproduce the
5206 // specific constants here because they are implicitly part of the Darwin ABI.
5207 enum {
5208 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5209 DARWIN_CPU_TYPE_X86 = 7,
5210 DARWIN_CPU_TYPE_ARM = 12,
5211 DARWIN_CPU_TYPE_POWERPC = 18
5212 };
5213
5214 Triple::ArchType Arch = TT.getArch();
5215 if (Arch == Triple::x86_64)
5216 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5217 else if (Arch == Triple::x86)
5218 CPUType = DARWIN_CPU_TYPE_X86;
5219 else if (Arch == Triple::ppc)
5220 CPUType = DARWIN_CPU_TYPE_POWERPC;
5221 else if (Arch == Triple::ppc64)
5222 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5223 else if (Arch == Triple::arm || Arch == Triple::thumb)
5224 CPUType = DARWIN_CPU_TYPE_ARM;
5225
5226 // Traditional Bitcode starts after header.
5227 assert(Buffer.size() >= BWH_HeaderSize &&
5228 "Expected header size to be reserved");
5229 unsigned BCOffset = BWH_HeaderSize;
5230 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
5231
5232 // Write the magic and version.
5233 unsigned Position = 0;
5234 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
5235 writeInt32ToBuffer(0, Buffer, Position); // Version.
5236 writeInt32ToBuffer(BCOffset, Buffer, Position);
5237 writeInt32ToBuffer(BCSize, Buffer, Position);
5238 writeInt32ToBuffer(CPUType, Buffer, Position);
5239
5240 // If the file is not a multiple of 16 bytes, insert dummy padding.
5241 while (Buffer.size() & 15)
5242 Buffer.push_back(0);
5243}
5244
5245/// Helper to write the header common to all bitcode files.
5247 // Emit the file header.
5248 Stream.Emit((unsigned)'B', 8);
5249 Stream.Emit((unsigned)'C', 8);
5250 Stream.Emit(0x0, 4);
5251 Stream.Emit(0xC, 4);
5252 Stream.Emit(0xE, 4);
5253 Stream.Emit(0xD, 4);
5254}
5255
5257 : Stream(new BitstreamWriter(Buffer)) {
5258 writeBitcodeHeader(*Stream);
5259}
5260
5262 : Stream(new BitstreamWriter(FS, FlushThreshold)) {
5263 writeBitcodeHeader(*Stream);
5264}
5265
5267
5268void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
5269 Stream->EnterSubblock(Block, 3);
5270
5271 auto Abbv = std::make_shared<BitCodeAbbrev>();
5272 Abbv->Add(BitCodeAbbrevOp(Record));
5274 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
5275
5276 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
5277
5278 Stream->ExitBlock();
5279}
5280
5282 assert(!WroteStrtab && !WroteSymtab);
5283
5284 // If any module has module-level inline asm, we will require a registered asm
5285 // parser for the target so that we can create an accurate symbol table for
5286 // the module.
5287 for (Module *M : Mods) {
5288 if (M->getModuleInlineAsm().empty())
5289 continue;
5290
5291 std::string Err;
5292 const Triple TT(M->getTargetTriple());
5293 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
5294 if (!T || !T->hasMCAsmParser())
5295 return;
5296 }
5297
5298 WroteSymtab = true;
5299 SmallVector<char, 0> Symtab;
5300 // The irsymtab::build function may be unable to create a symbol table if the
5301 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
5302 // table is not required for correctness, but we still want to be able to
5303 // write malformed modules to bitcode files, so swallow the error.
5304 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
5305 consumeError(std::move(E));
5306 return;
5307 }
5308
5310 {Symtab.data(), Symtab.size()});
5311}
5312
5314 assert(!WroteStrtab);
5315
5316 std::vector<char> Strtab;
5317 StrtabBuilder.finalizeInOrder();
5318 Strtab.resize(StrtabBuilder.getSize());
5319 StrtabBuilder.write((uint8_t *)Strtab.data());
5320
5322 {Strtab.data(), Strtab.size()});
5323
5324 WroteStrtab = true;
5325}
5326
5328 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
5329 WroteStrtab = true;
5330}
5331
5333 bool ShouldPreserveUseListOrder,
5334 const ModuleSummaryIndex *Index,
5335 bool GenerateHash, ModuleHash *ModHash) {
5336 assert(!WroteStrtab);
5337
5338 // The Mods vector is used by irsymtab::build, which requires non-const
5339 // Modules in case it needs to materialize metadata. But the bitcode writer
5340 // requires that the module is materialized, so we can cast to non-const here,
5341 // after checking that it is in fact materialized.
5342 assert(M.isMaterialized());
5343 Mods.push_back(const_cast<Module *>(&M));
5344
5345 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5346 ShouldPreserveUseListOrder, Index,
5347 GenerateHash, ModHash);
5348 ModuleWriter.write();
5349}
5350
5352 const ModuleSummaryIndex *Index,
5353 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5354 const GVSummaryPtrSet *DecSummaries) {
5355 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5356 ModuleToSummariesForIndex);
5357 IndexWriter.write();
5358}
5359
5360/// Write the specified module to the specified output stream.
5362 bool ShouldPreserveUseListOrder,
5363 const ModuleSummaryIndex *Index,
5364 bool GenerateHash, ModuleHash *ModHash) {
5365 auto Write = [&](BitcodeWriter &Writer) {
5366 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5367 ModHash);
5368 Writer.writeSymtab();
5369 Writer.writeStrtab();
5370 };
5371 Triple TT(M.getTargetTriple());
5372 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5373 // If this is darwin or another generic macho target, reserve space for the
5374 // header. Note that the header is computed *after* the output is known, so
5375 // we currently explicitly use a buffer, write to it, and then subsequently
5376 // flush to Out.
5377 SmallVector<char, 0> Buffer;
5378 Buffer.reserve(256 * 1024);
5379 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
5380 BitcodeWriter Writer(Buffer);
5381 Write(Writer);
5382 emitDarwinBCHeaderAndTrailer(Buffer, TT);
5383 Out.write(Buffer.data(), Buffer.size());
5384 } else {
5385 BitcodeWriter Writer(Out);
5386 Write(Writer);
5387 }
5388}
5389
5390void IndexBitcodeWriter::write() {
5392
5393 writeModuleVersion();
5394
5395 // Write the module paths in the combined index.
5396 writeModStrings();
5397
5398 // Write the summary combined index records.
5399 writeCombinedGlobalValueSummary();
5400
5401 Stream.ExitBlock();
5402}
5403
5404// Write the specified module summary index to the given raw output stream,
5405// where it will be written in a new bitcode block. This is used when
5406// writing the combined index file for ThinLTO. When writing a subset of the
5407// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
5409 const ModuleSummaryIndex &Index, raw_ostream &Out,
5410 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5411 const GVSummaryPtrSet *DecSummaries) {
5412 SmallVector<char, 0> Buffer;
5413 Buffer.reserve(256 * 1024);
5414
5415 BitcodeWriter Writer(Buffer);
5416 Writer.writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5417 Writer.writeStrtab();
5418
5419 Out.write((char *)&Buffer.front(), Buffer.size());
5420}
5421
5422namespace {
5423
5424/// Class to manage the bitcode writing for a thin link bitcode file.
5425class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
5426 /// ModHash is for use in ThinLTO incremental build, generated while writing
5427 /// the module bitcode file.
5428 const ModuleHash *ModHash;
5429
5430public:
5431 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
5432 BitstreamWriter &Stream,
5434 const ModuleHash &ModHash)
5435 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5436 /*ShouldPreserveUseListOrder=*/false, &Index),
5437 ModHash(&ModHash) {}
5438
5439 void write();
5440
5441private:
5442 void writeSimplifiedModuleInfo();
5443};
5444
5445} // end anonymous namespace
5446
5447// This function writes a simpilified module info for thin link bitcode file.
5448// It only contains the source file name along with the name(the offset and
5449// size in strtab) and linkage for global values. For the global value info
5450// entry, in order to keep linkage at offset 5, there are three zeros used
5451// as padding.
5452void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5454 // Emit the module's source file name.
5455 {
5456 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
5458 if (Bits == SE_Char6)
5459 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
5460 else if (Bits == SE_Fixed7)
5461 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
5462
5463 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5464 auto Abbv = std::make_shared<BitCodeAbbrev>();
5467 Abbv->Add(AbbrevOpToUse);
5468 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5469
5470 for (const auto P : M.getSourceFileName())
5471 Vals.push_back((unsigned char)P);
5472
5473 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
5474 Vals.clear();
5475 }
5476
5477 // Emit the global variable information.
5478 for (const GlobalVariable &GV : M.globals()) {
5479 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
5480 Vals.push_back(StrtabBuilder.add(GV.getName()));
5481 Vals.push_back(GV.getName().size());
5482 Vals.push_back(0);
5483 Vals.push_back(0);
5484 Vals.push_back(0);
5485 Vals.push_back(getEncodedLinkage(GV));
5486
5488 Vals.clear();
5489 }
5490
5491 // Emit the function proto information.
5492 for (const Function &F : M) {
5493 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
5494 Vals.push_back(StrtabBuilder.add(F.getName()));
5495 Vals.push_back(F.getName().size());
5496 Vals.push_back(0);
5497 Vals.push_back(0);
5498 Vals.push_back(0);
5500
5502 Vals.clear();
5503 }
5504
5505 // Emit the alias information.
5506 for (const GlobalAlias &A : M.aliases()) {
5507 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
5508 Vals.push_back(StrtabBuilder.add(A.getName()));
5509 Vals.push_back(A.getName().size());
5510 Vals.push_back(0);
5511 Vals.push_back(0);
5512 Vals.push_back(0);
5514
5515 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
5516 Vals.clear();
5517 }
5518
5519 // Emit the ifunc information.
5520 for (const GlobalIFunc &I : M.ifuncs()) {
5521 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
5522 Vals.push_back(StrtabBuilder.add(I.getName()));
5523 Vals.push_back(I.getName().size());
5524 Vals.push_back(0);
5525 Vals.push_back(0);
5526 Vals.push_back(0);
5528
5529 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
5530 Vals.clear();
5531 }
5532}
5533
5534void ThinLinkBitcodeWriter::write() {
5536
5537 writeModuleVersion();
5538
5539 writeSimplifiedModuleInfo();
5540
5541 writePerModuleGlobalValueSummary();
5542
5543 // Write module hash.
5545
5546 Stream.ExitBlock();
5547}
5548
5550 const ModuleSummaryIndex &Index,
5551 const ModuleHash &ModHash) {
5552 assert(!WroteStrtab);
5553
5554 // The Mods vector is used by irsymtab::build, which requires non-const
5555 // Modules in case it needs to materialize metadata. But the bitcode writer
5556 // requires that the module is materialized, so we can cast to non-const here,
5557 // after checking that it is in fact materialized.
5558 assert(M.isMaterialized());
5559 Mods.push_back(const_cast<Module *>(&M));
5560
5561 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
5562 ModHash);
5563 ThinLinkWriter.write();
5564}
5565
5566// Write the specified thin link bitcode file to the given raw output stream,
5567// where it will be written in a new bitcode block. This is used when
5568// writing the per-module index file for ThinLTO.
5570 const ModuleSummaryIndex &Index,
5571 const ModuleHash &ModHash) {
5572 SmallVector<char, 0> Buffer;
5573 Buffer.reserve(256 * 1024);
5574
5575 BitcodeWriter Writer(Buffer);
5576 Writer.writeThinLinkBitcode(M, Index, ModHash);
5577 Writer.writeSymtab();
5578 Writer.writeStrtab();
5579
5580 Out.write((char *)&Buffer.front(), Buffer.size());
5581}
5582
5583static const char *getSectionNameForBitcode(const Triple &T) {
5584 switch (T.getObjectFormat()) {
5585 case Triple::MachO:
5586 return "__LLVM,__bitcode";
5587 case Triple::COFF:
5588 case Triple::ELF:
5589 case Triple::Wasm:
5591 return ".llvmbc";
5592 case Triple::GOFF:
5593 llvm_unreachable("GOFF is not yet implemented");
5594 break;
5595 case Triple::SPIRV:
5596 if (T.getVendor() == Triple::AMD)
5597 return ".llvmbc";
5598 llvm_unreachable("SPIRV is not yet implemented");
5599 break;
5600 case Triple::XCOFF:
5601 llvm_unreachable("XCOFF is not yet implemented");
5602 break;
5604 llvm_unreachable("DXContainer is not yet implemented");
5605 break;
5606 }
5607 llvm_unreachable("Unimplemented ObjectFormatType");
5608}
5609
5610static const char *getSectionNameForCommandline(const Triple &T) {
5611 switch (T.getObjectFormat()) {
5612 case Triple::MachO:
5613 return "__LLVM,__cmdline";
5614 case Triple::COFF:
5615 case Triple::ELF:
5616 case Triple::Wasm:
5618 return ".llvmcmd";
5619 case Triple::GOFF:
5620 llvm_unreachable("GOFF is not yet implemented");
5621 break;
5622 case Triple::SPIRV:
5623 if (T.getVendor() == Triple::AMD)
5624 return ".llvmcmd";
5625 llvm_unreachable("SPIRV is not yet implemented");
5626 break;
5627 case Triple::XCOFF:
5628 llvm_unreachable("XCOFF is not yet implemented");
5629 break;
5631 llvm_unreachable("DXC is not yet implemented");
5632 break;
5633 }
5634 llvm_unreachable("Unimplemented ObjectFormatType");
5635}
5636
5638 bool EmbedBitcode, bool EmbedCmdline,
5639 const std::vector<uint8_t> &CmdArgs) {
5640 // Save llvm.compiler.used and remove it.
5643 GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
5644 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
5645 : PointerType::getUnqual(M.getContext());
5646 for (auto *GV : UsedGlobals) {
5647 if (GV->getName() != "llvm.embedded.module" &&
5648 GV->getName() != "llvm.cmdline")
5649 UsedArray.push_back(
5651 }
5652 if (Used)
5653 Used->eraseFromParent();
5654
5655 // Embed the bitcode for the llvm module.
5656 std::string Data;
5657 ArrayRef<uint8_t> ModuleData;
5658 Triple T(M.getTargetTriple());
5659
5660 if (EmbedBitcode) {
5661 if (Buf.getBufferSize() == 0 ||
5662 !isBitcode((const unsigned char *)Buf.getBufferStart(),
5663 (const unsigned char *)Buf.getBufferEnd())) {
5664 // If the input is LLVM Assembly, bitcode is produced by serializing
5665 // the module. Use-lists order need to be preserved in this case.
5667 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
5668 ModuleData =
5669 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
5670 } else
5671 // If the input is LLVM bitcode, write the input byte stream directly.
5672 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
5673 Buf.getBufferSize());
5674 }
5675 llvm::Constant *ModuleConstant =
5676 llvm::ConstantDataArray::get(M.getContext(), ModuleData);
5678 M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
5679 ModuleConstant);
5681 // Set alignment to 1 to prevent padding between two contributions from input
5682 // sections after linking.
5683 GV->setAlignment(Align(1));
5684 UsedArray.push_back(
5686 if (llvm::GlobalVariable *Old =
5687 M.getGlobalVariable("llvm.embedded.module", true)) {
5688 assert(Old->hasZeroLiveUses() &&
5689 "llvm.embedded.module can only be used once in llvm.compiler.used");
5690 GV->takeName(Old);
5691 Old->eraseFromParent();
5692 } else {
5693 GV->setName("llvm.embedded.module");
5694 }
5695
5696 // Skip if only bitcode needs to be embedded.
5697 if (EmbedCmdline) {
5698 // Embed command-line options.
5699 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
5700 CmdArgs.size());
5701 llvm::Constant *CmdConstant =
5702 llvm::ConstantDataArray::get(M.getContext(), CmdData);
5703 GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
5705 CmdConstant);
5707 GV->setAlignment(Align(1));
5708 UsedArray.push_back(
5710 if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
5711 assert(Old->hasZeroLiveUses() &&
5712 "llvm.cmdline can only be used once in llvm.compiler.used");
5713 GV->takeName(Old);
5714 Old->eraseFromParent();
5715 } else {
5716 GV->setName("llvm.cmdline");
5717 }
5718 }
5719
5720 if (UsedArray.empty())
5721 return;
5722
5723 // Recreate llvm.compiler.used.
5724 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
5725 auto *NewUsed = new GlobalVariable(
5727 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
5728 NewUsed->setSection("llvm.metadata");
5729}
This file defines the StringMap class.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void writeDIMacro(raw_ostream &Out, const DIMacro *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2392
static void writeDIGlobalVariableExpression(raw_ostream &Out, const DIGlobalVariableExpression *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2539
static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2227
static void writeDIStringType(raw_ostream &Out, const DIStringType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2176
static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2453
static void writeDIModule(raw_ostream &Out, const DIModule *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2413
static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &)
Definition: AsmWriter.cpp:2274
static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2263
static void writeDILabel(raw_ostream &Out, const DILabel *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2488
static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2194
static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2563
static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2549
static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2319
static void writeDILocation(raw_ostream &Out, const DILocation *DL, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2036
static void writeDINamespace(raw_ostream &Out, const DINamespace *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2370
static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2380
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, AsmWriterContext &)
Definition: AsmWriter.cpp:2160
static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2018
static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2472
static void writeDITemplateTypeParameter(raw_ostream &Out, const DITemplateTypeParameter *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2428
static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2289
static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2097
static void writeDISubrange(raw_ostream &Out, const DISubrange *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2056
static void writeDILexicalBlockFile(raw_ostream &Out, const DILexicalBlockFile *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2358
static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, AsmWriterContext &)
Definition: AsmWriter.cpp:2148
static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:1797
static void writeDIExpression(raw_ostream &Out, const DIExpression *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2499
static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2050
static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2347
static void writeDIArgList(raw_ostream &Out, const DIArgList *N, AsmWriterContext &WriterCtx, bool FromValue=false)
Definition: AsmWriter.cpp:2524
static void writeDITemplateValueParameter(raw_ostream &Out, const DITemplateValueParameter *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2439
static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2403
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void writeFunctionHeapProfileRecords(BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev, unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule, std::function< unsigned(const ValueInfo &VI)> GetValueID, std::function< unsigned(unsigned)> GetStackIndex, bool WriteContextSizeInfoIndex, DenseMap< CallStackId, LinearCallStackId > &CallStackPos, CallStackId &CallStackCount)
static unsigned serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta)
static void writeTypeIdCompatibleVtableSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdCompatibleVtableInfo &Summary, ValueEnumerator &VE)
static void getReferencedTypeIds(FunctionSummary *FS, std::set< GlobalValue::GUID > &ReferencedTypeIds)
Collect type IDs from type tests used by function.
static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind)
static void collectMemProfCallStacks(FunctionSummary *FS, std::function< LinearFrameId(unsigned)> GetStackIndex, MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &CallStacks)
static unsigned getEncodedUnaryOpcode(unsigned Opcode)
static void emitSignedInt64(SmallVectorImpl< uint64_t > &Vals, uint64_t V)
StringEncoding
@ SE_Char6
@ SE_Fixed7
@ SE_Fixed8
static unsigned getEncodedVisibility(const GlobalValue &GV)
static uint64_t getOptimizationFlags(const Value *V)
static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage)
static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op)
static unsigned getEncodedThreadLocalMode(const GlobalValue &GV)
static DenseMap< CallStackId, LinearCallStackId > writeMemoryProfileRadixTree(MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &&CallStacks, BitstreamWriter &Stream, unsigned RadixAbbrev)
static void writeIdentificationBlock(BitstreamWriter &Stream)
Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the current llvm version,...
static unsigned getEncodedCastOpcode(unsigned Opcode)
static cl::opt< bool > WriteRelBFToSummary("write-relbf-to-summary", cl::Hidden, cl::init(false), cl::desc("Write relative block frequency to function summary "))
static cl::opt< uint32_t > FlushThreshold("bitcode-flush-threshold", cl::Hidden, cl::init(512), cl::desc("The threshold (unit M) for flushing LLVM bitcode."))
static unsigned getEncodedOrdering(AtomicOrdering Ordering)
static unsigned getEncodedUnnamedAddr(const GlobalValue &GV)
bool WriteNewDbgInfoFormatToBitcode
Definition: BasicBlock.cpp:47
static unsigned getEncodedComdatSelectionKind(const Comdat &C)
static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags, bool ImportAsDecl=false)
static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl< char > &Buffer, const Triple &TT)
If generating a bc file on darwin, we have to emit a header and trailer to make it compatible with th...
static void writeBitcodeHeader(BitstreamWriter &Stream)
Helper to write the header common to all bitcode files.
llvm::cl::opt< bool > UseNewDbgInfoFormat
static uint64_t getEncodedRelBFCallEdgeInfo(const CalleeInfo &CI)
static void writeWholeProgramDevirtResolutionByArg(SmallVector< uint64_t, 64 > &NameVals, const std::vector< uint64_t > &args, const WholeProgramDevirtResolution::ByArg &ByArg)
static void emitConstantRange(SmallVectorImpl< uint64_t > &Record, const ConstantRange &CR, bool EmitBitWidth)
static StringEncoding getStringEncoding(StringRef Str)
Determine the encoding to use for the given string name and length.
static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags)
static const char * getSectionNameForCommandline(const Triple &T)
static cl::opt< unsigned > IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25), cl::desc("Number of metadatas above which we emit an index " "to enable lazy-loading"))
static void writeTypeIdSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdSummary &Summary)
static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream, FunctionSummary *FS, Fn GetValueID)
Write the function type metadata related records that need to appear before a function summary entry ...
static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI)
static void emitWideAPInt(SmallVectorImpl< uint64_t > &Vals, const APInt &A)
static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, StringRef Str, unsigned AbbrevToUse)
static void writeWholeProgramDevirtResolution(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, uint64_t Id, const WholeProgramDevirtResolution &Wpd)
static unsigned getEncodedDLLStorageClass(const GlobalValue &GV)
static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl< char > &Buffer, uint32_t &Position)
MetadataAbbrev
@ LastPlusOne
static const char * getSectionNameForBitcode(const Triple &T)
static unsigned getEncodedBinaryOpcode(unsigned Opcode)
static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines the DenseMap class.
std::string Name
uint32_t Index
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Hexagon Common GEP
#define _
static MaybeAlign getAlign(Value *Ptr)
Definition: IRBuilder.cpp:500
Module.h This file contains the declarations for the Module class.
static cl::opt< LTOBitcodeEmbedding > EmbedBitcode("lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed), cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none", "Do not embed"), clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized", "Embed after all optimization passes"), clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized, "post-merge-pre-opt", "Embed post merge, but before optimizations")), cl::desc("Embed LLVM bitcode in object files produced by LTO"))
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
#define H(x, y, z)
Definition: MD5.cpp:57
This file contains the declarations for metadata subclasses.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
nvptx lower args
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static const uint32_t IV[8]
Definition: blake3_impl.h:78
Class for arbitrary precision integers.
Definition: APInt.h:78
unsigned getNumWords() const
Get the number of words.
Definition: APInt.h:1475
unsigned getActiveWords() const
Compute the number of active words in the value of this APInt.
Definition: APInt.h:1498
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition: APInt.h:569
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1542
Alias summary information.
const GlobalValueSummary & getAliasee() const
an instruction to allocate memory on the stack
Definition: Instructions.h:63
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Definition: Instructions.h:149
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:124
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:117
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
Definition: Instructions.h:139
unsigned getAddressSpace() const
Return the address space for the allocation.
Definition: Instructions.h:104
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:168
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:163
Class to represent array types.
Definition: DerivedTypes.h:395
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
Definition: Instructions.h:716
@ Add
*p = old + v
Definition: Instructions.h:720
@ FAdd
*p = old + v
Definition: Instructions.h:741
@ USubCond
Subtract only if no unsigned overflow.
Definition: Instructions.h:764
@ Min
*p = old <signed v ? old : v
Definition: Instructions.h:734
@ Or
*p = old | v
Definition: Instructions.h:728
@ Sub
*p = old - v
Definition: Instructions.h:722
@ And
*p = old & v
Definition: Instructions.h:724
@ Xor
*p = old ^ v
Definition: Instructions.h:730
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
Definition: Instructions.h:768
@ FSub
*p = old - v
Definition: Instructions.h:744
@ UIncWrap
Increment one up to a maximum value.
Definition: Instructions.h:756
@ Max
*p = old >signed v ? old : v
Definition: Instructions.h:732
@ UMin
*p = old <unsigned v ? old : v
Definition: Instructions.h:738
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
Definition: Instructions.h:752
@ UMax
*p = old >unsigned v ? old : v
Definition: Instructions.h:736
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
Definition: Instructions.h:748
@ UDecWrap
Decrement one until a minimum value or zero.
Definition: Instructions.h:760
@ Nand
*p = ~(old & v)
Definition: Instructions.h:726
bool hasAttributes() const
Return true if attributes exists in this set.
Definition: Attributes.h:408
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition: Attributes.h:86
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
Definition: Attributes.h:93
@ None
No attributes have been set.
Definition: Attributes.h:88
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
Definition: Attributes.h:92
@ EndAttrKinds
Sentinel value useful for loops.
Definition: Attributes.h:91
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
Definition: BitCodes.h:33
static bool isChar6(char C)
isChar6 - Return true if this character is legal in the Char6 encoding.
Definition: BitCodes.h:82
void writeThinLinkBitcode(const Module &M, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the buffer specified...
void writeIndex(const ModuleSummaryIndex *Index, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex, const GVSummaryPtrSet *DecSummaries)
void copyStrtab(StringRef Strtab)
Copy the string table for another module into this bitcode file.
void writeStrtab()
Write the bitcode file's string table.
void writeSymtab()
Attempt to write a symbol table to the bitcode file.
void writeModule(const Module &M, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the buffer specified at construction time.
BitcodeWriter(SmallVectorImpl< char > &Buffer)
Create a BitcodeWriter that writes to Buffer.
unsigned EmitAbbrev(std::shared_ptr< BitCodeAbbrev > Abbv)
Emits the abbreviation Abbv to the stream.
void markAndBlockFlushing()
For scenarios where the user wants to access a section of the stream to (for example) compute some ch...
StringRef getMarkedBufferAndResumeFlushing()
resumes flushing, but does not flush, and returns the section in the internal buffer starting from th...
void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev=0)
EmitRecord - Emit the specified record to the stream, using an abbrev if we have one to compress the ...
void Emit(uint32_t Val, unsigned NumBits)
void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals, StringRef Blob)
EmitRecordWithBlob - Emit the specified record to the stream, using an abbrev that includes a blob at...
unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr< BitCodeAbbrev > Abbv)
EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified BlockID.
void EnterBlockInfoBlock()
EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
void BackpatchWord(uint64_t BitNo, unsigned Val)
void BackpatchWord64(uint64_t BitNo, uint64_t Val)
void EnterSubblock(unsigned BlockID, unsigned CodeLen)
uint64_t GetCurrentBitNo() const
Retrieve the current position in the stream, in bits.
void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals)
EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
The address of a basic block.
Definition: Constants.h:893
static BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Definition: Constants.cpp:1915
Conditional or Unconditional Branch instruction.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1120
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
Definition: InstrTypes.h:2020
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
Definition: InstrTypes.h:1964
CallingConv::ID getCallingConv() const
Definition: InstrTypes.h:1407
Value * getCalledOperand() const
Definition: InstrTypes.h:1342
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1294
FunctionType * getFunctionType() const
Definition: InstrTypes.h:1207
unsigned arg_size() const
Definition: InstrTypes.h:1292
AttributeList getAttributes() const
Return the attributes for this call.
Definition: InstrTypes.h:1425
bool hasOperandBundles() const
Return true if this User has any operand bundles.
Definition: InstrTypes.h:1969
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
BasicBlock * getIndirectDest(unsigned i) const
BasicBlock * getDefaultDest() const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
This class represents a function call, abstracting a target machine's calling convention.
bool isNoTailCall() const
bool isTailCall() const
bool isMustTailCall() const
@ Largest
The linker will choose the largest COMDAT.
Definition: Comdat.h:38
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:40
@ Any
The linker may choose any COMDAT.
Definition: Comdat.h:36
@ NoDeduplicate
No deduplication is performed.
Definition: Comdat.h:39
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition: Comdat.h:37
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1312
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition: Constants.h:709
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:587
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:1108
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:2268
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:271
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
This class represents a range of values.
Definition: ConstantRange.h:47
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
This is an important base class in LLVM.
Definition: Constant.h:42
List of ValueAsMetadata, to be used as an argument to a dbg.value intrinsic.
Assignment ID.
Basic type, like 'int' or 'float'.
Debug common block.
Enumeration value.
DWARF expression.
A pair of DIGlobalVariable and DIExpression.
An imported module (C++ using directive or similar).
Debug lexical block.
Debug location.
Represents a module in the programming language, for example, a Clang module, or a Fortran module.
Debug lexical block.
String type, Fortran CHARACTER(n)
Subprogram description.
Array subrange.
Type array for a subprogram.
This class represents an Operation in the Expression.
Records a position in IR for a source label (DILabel).
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
DIExpression * getExpression() const
DILocalVariable * getVariable() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
DIExpression * getAddressExpression() const
unsigned size() const
Definition: DenseMap.h:99
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:152
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:147
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:211
Implements a dense probed hash-table based set.
Definition: DenseSet.h:278
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
This instruction extracts a struct member or array element value from an aggregate value.
idx_iterator idx_end() const
idx_iterator idx_begin() const
Function summary information to aid decisions and implementation of importing.
ForceSummaryHotnessType
Types for -force-summary-edges-cold debugging option.
Generic tagged DWARF-like metadata node.
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
Definition: Metadata.cpp:1521
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:143
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:273
Function and variable summary information to aid decisions and implementation of importing.
GVFlags flags() const
Get the flags for this GlobalValue (see struct GVFlags).
StringRef modulePath() const
Get the path to the module containing this function.
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:248
static bool isLocalLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:409
LinkageTypes getLinkage() const
Definition: GlobalValue.h:546
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
Definition: GlobalValue.h:567
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:271
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition: GlobalValue.h:76
@ DLLImportStorageClass
Function to be imported from DLL.
Definition: GlobalValue.h:75
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:595
@ DefaultVisibility
The GV is visible.
Definition: GlobalValue.h:67
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
@ ProtectedVisibility
The GV is protected.
Definition: GlobalValue.h:69
UnnamedAddr getUnnamedAddr() const
Definition: GlobalValue.h:228
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:51
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
@ CommonLinkage
Tentative definitions.
Definition: GlobalValue.h:62
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:54
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:57
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:56
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:58
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition: GlobalValue.h:53
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:61
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:55
DLLStorageClassTypes getDLLStorageClass() const
Definition: GlobalValue.h:275
Global variable summary information to aid decisions and implementation of importing.
This instruction inserts a struct field of array element value into an aggregate value.
idx_iterator idx_end() const
idx_iterator idx_begin() const
bool isCast() const
Definition: Instruction.h:283
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
The landingpad instruction holds all of the information necessary to generate correct exception handl...
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
Metadata node.
Definition: Metadata.h:1069
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:891
Tuple of metadata.
Definition: Metadata.h:1473
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
bool empty() const
Definition: MapVector.h:79
size_t getBufferSize() const
const char * getBufferStart() const
const char * getBufferEnd() const
Root of the metadata hierarchy.
Definition: Metadata.h:62
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static constexpr uint64_t BitcodeSummaryVersion
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A tuple of MDNodes.
Definition: Metadata.h:1731
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Definition: DerivedTypes.h:686
A class that wrap the SHA1 algorithm.
Definition: SHA1.h:26
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:98
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:93
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
void append(StringRef RHS)
Append from a StringRef.
Definition: SmallString.h:68
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
void assign(size_type NumElts, ValueParamT Elt)
Definition: SmallVector.h:704
void reserve(size_type N)
Definition: SmallVector.h:663
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:683
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:805
void resize(size_type N)
Definition: SmallVector.h:638
void push_back(const T &Elt)
Definition: SmallVector.h:413
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:286
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
const ValueTy & getValue() const
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
StringRef getKey() const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
iterator begin() const
Definition: StringRef.h:116
iterator end() const
Definition: StringRef.h:118
Utility for building string tables with deduplicated suffixes.
void finalizeInOrder()
Finalize the string table without reording it.
void write(raw_ostream &OS) const
size_t add(CachedHashStringRef S)
Add a string to the builder.
Class to represent struct types.
Definition: DerivedTypes.h:218
Multiway switch.
Class to represent target extensions types, which are generally unintrospectable from target-independ...
Definition: DerivedTypes.h:744
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
@ DXContainer
Definition: Triple.h:311
@ UnknownObjectFormat
Definition: Triple.h:308
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isX86_FP80Ty() const
Return true if this is x86 long double.
Definition: Type.h:159
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:153
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition: Type.h:145
@ X86_AMXTyID
AMX vectors (8192 bits, X86 specific)
Definition: Type.h:66
@ FunctionTyID
Functions.
Definition: Type.h:71
@ ArrayTyID
Arrays.
Definition: Type.h:74
@ TypedPointerTyID
Typed pointer used by some GPU targets.
Definition: Type.h:77
@ HalfTyID
16-bit floating point type
Definition: Type.h:56
@ TargetExtTyID
Target extension type.
Definition: Type.h:78
@ VoidTyID
type with no size
Definition: Type.h:63
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition: Type.h:76
@ LabelTyID
Labels.
Definition: Type.h:64
@ FloatTyID
32-bit floating point type
Definition: Type.h:58
@ StructTyID
Structures.
Definition: Type.h:73
@ IntegerTyID
Arbitrary bit width integers.
Definition: Type.h:70
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition: Type.h:75
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition: Type.h:57
@ DoubleTyID
64-bit floating point type
Definition: Type.h:59
@ X86_FP80TyID
80-bit floating point type (X87)
Definition: Type.h:60
@ PPC_FP128TyID
128-bit floating point type (two 64-bits, PowerPC)
Definition: Type.h:62
@ MetadataTyID
Metadata.
Definition: Type.h:65
@ TokenTyID
Tokens.
Definition: Type.h:67
@ PointerTyID
Pointers.
Definition: Type.h:72
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition: Type.h:61
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition: Type.h:165
bool isFP128Ty() const
Return true if this is 'fp128'.
Definition: Type.h:162
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition: Type.h:142
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition: Type.h:156
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:355
Value wrapper in the Metadata hierarchy.
Definition: Metadata.h:450
Value * getValue() const
Definition: Metadata.h:490
unsigned getTypeID(Type *T) const
unsigned getMetadataID(const Metadata *MD) const
UseListOrderStack UseListOrders
std::vector< std::pair< const Value *, unsigned > > ValueList
ArrayRef< const Metadata * > getNonMDStrings() const
Get the non-MDString metadata for this block.
unsigned getInstructionID(const Instruction *I) const
unsigned getAttributeListID(AttributeList PAL) const
void incorporateFunction(const Function &F)
incorporateFunction/purgeFunction - If you'd like to deal with a function, use these two methods to g...
void getFunctionConstantRange(unsigned &Start, unsigned &End) const
getFunctionConstantRange - Return the range of values that corresponds to function-local constants.
unsigned getAttributeGroupID(IndexAndAttrSet Group) const
bool hasMDs() const
Check whether the current block has any metadata to emit.
unsigned getComdatID(const Comdat *C) const
uint64_t computeBitsRequiredForTypeIndices() const
unsigned getValueID(const Value *V) const
unsigned getMetadataOrNullID(const Metadata *MD) const
const std::vector< IndexAndAttrSet > & getAttributeGroups() const
const ValueList & getValues() const
unsigned getGlobalBasicBlockID(const BasicBlock *BB) const
getGlobalBasicBlockID - This returns the function-specific ID for the specified basic block.
void setInstructionID(const Instruction *I)
const std::vector< const BasicBlock * > & getBasicBlocks() const
const std::vector< AttributeList > & getAttributeLists() const
bool shouldPreserveUseListOrder() const
const ComdatSetType & getComdats() const
std::vector< Type * > TypeList
ArrayRef< const Metadata * > getMDStrings() const
Get the MDString metadata for this block.
std::pair< unsigned, AttributeSet > IndexAndAttrSet
Attribute groups as encoded in bitcode are almost AttributeSets, but they include the AttributeList i...
const TypeList & getTypes() const
This class provides a symbol table of name/value pairs.
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1075
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:213
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:193
void build(llvm::MapVector< CallStackId, llvm::SmallVector< FrameIdTy > > &&MemProfCallStackData, const llvm::DenseMap< FrameIdTy, LinearFrameId > *MemProfFrameIndexes, llvm::DenseMap< FrameIdTy, FrameStat > &FrameHistogram)
Definition: MemProf.cpp:380
ArrayRef< LinearFrameId > getRadixArray() const
Definition: MemProf.h:1168
llvm::DenseMap< CallStackId, LinearCallStackId > takeCallStackPos()
Definition: MemProf.h:1170
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
raw_ostream & write(unsigned char C)
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Key
PAL metadata keys.
@ Entry
Definition: COFF.h:844
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
const uint64_t Version
Definition: CodeGenData.h:286
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
Definition: PPCPredicates.h:87
@ CE
Windows NT (Windows on ARM)
@ FS
Definition: X86.h:211
@ BITCODE_CURRENT_EPOCH
Definition: LLVMBitCodes.h:81
@ TYPE_CODE_METADATA
Definition: LLVMBitCodes.h:162
@ TYPE_CODE_PPC_FP128
Definition: LLVMBitCodes.h:160
@ TYPE_CODE_TARGET_TYPE
Definition: LLVMBitCodes.h:179
@ TYPE_CODE_STRUCT_ANON
Definition: LLVMBitCodes.h:166
@ TYPE_CODE_STRUCT_NAME
Definition: LLVMBitCodes.h:167
@ TYPE_CODE_X86_FP80
Definition: LLVMBitCodes.h:158
@ TYPE_CODE_OPAQUE_POINTER
Definition: LLVMBitCodes.h:177
@ TYPE_CODE_FUNCTION
Definition: LLVMBitCodes.h:170
@ TYPE_CODE_NUMENTRY
Definition: LLVMBitCodes.h:136
@ TYPE_CODE_STRUCT_NAMED
Definition: LLVMBitCodes.h:168
@ METADATA_NAMESPACE
Definition: LLVMBitCodes.h:364
@ METADATA_COMMON_BLOCK
Definition: LLVMBitCodes.h:384
@ METADATA_STRING_TYPE
Definition: LLVMBitCodes.h:381
@ METADATA_MACRO_FILE
Definition: LLVMBitCodes.h:374
@ METADATA_TEMPLATE_VALUE
Definition: LLVMBitCodes.h:366
@ METADATA_LEXICAL_BLOCK_FILE
Definition: LLVMBitCodes.h:363
@ METADATA_INDEX_OFFSET
Definition: LLVMBitCodes.h:378
@ METADATA_LEXICAL_BLOCK
Definition: LLVMBitCodes.h:362
@ METADATA_SUBPROGRAM
Definition: LLVMBitCodes.h:361
@ METADATA_SUBROUTINE_TYPE
Definition: LLVMBitCodes.h:359
@ METADATA_GLOBAL_DECL_ATTACHMENT
Definition: LLVMBitCodes.h:376
@ METADATA_LOCAL_VAR
Definition: LLVMBitCodes.h:368
@ METADATA_GLOBAL_VAR
Definition: LLVMBitCodes.h:367
@ METADATA_EXPRESSION
Definition: LLVMBitCodes.h:369
@ METADATA_ATTACHMENT
Definition: LLVMBitCodes.h:351
@ METADATA_OBJC_PROPERTY
Definition: LLVMBitCodes.h:370
@ METADATA_NAMED_NODE
Definition: LLVMBitCodes.h:350
@ METADATA_IMPORTED_ENTITY
Definition: LLVMBitCodes.h:371
@ METADATA_GENERIC_SUBRANGE
Definition: LLVMBitCodes.h:385
@ METADATA_ASSIGN_ID
Definition: LLVMBitCodes.h:387
@ METADATA_COMPILE_UNIT
Definition: LLVMBitCodes.h:360
@ METADATA_COMPOSITE_TYPE
Definition: LLVMBitCodes.h:358
@ METADATA_ENUMERATOR
Definition: LLVMBitCodes.h:354
@ METADATA_DERIVED_TYPE
Definition: LLVMBitCodes.h:357
@ METADATA_TEMPLATE_TYPE
Definition: LLVMBitCodes.h:365
@ METADATA_GLOBAL_VAR_EXPR
Definition: LLVMBitCodes.h:377
@ METADATA_BASIC_TYPE
Definition: LLVMBitCodes.h:355
@ METADATA_DISTINCT_NODE
Definition: LLVMBitCodes.h:345
@ METADATA_GENERIC_DEBUG
Definition: LLVMBitCodes.h:352
@ FS_CONTEXT_RADIX_TREE_ARRAY
Definition: LLVMBitCodes.h:337
@ FS_CFI_FUNCTION_DEFS
Definition: LLVMBitCodes.h:263
@ FS_PERMODULE_RELBF
Definition: LLVMBitCodes.h:272
@ FS_COMBINED_GLOBALVAR_INIT_REFS
Definition: LLVMBitCodes.h:225
@ FS_TYPE_CHECKED_LOAD_VCALLS
Definition: LLVMBitCodes.h:247
@ FS_COMBINED_PROFILE
Definition: LLVMBitCodes.h:223
@ FS_ALLOC_CONTEXT_IDS
Definition: LLVMBitCodes.h:333
@ FS_COMBINED_ORIGINAL_NAME
Definition: LLVMBitCodes.h:231
@ FS_TYPE_ID_METADATA
Definition: LLVMBitCodes.h:294
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
Definition: LLVMBitCodes.h:300
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
Definition: LLVMBitCodes.h:251
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
Definition: LLVMBitCodes.h:216
@ FS_TYPE_TEST_ASSUME_VCALLS
Definition: LLVMBitCodes.h:242
@ FS_CFI_FUNCTION_DECLS
Definition: LLVMBitCodes.h:267
@ FS_COMBINED_CALLSITE_INFO
Definition: LLVMBitCodes.h:316
@ FS_COMBINED_ALLOC_INFO
Definition: LLVMBitCodes.h:321
@ FS_PERMODULE_PROFILE
Definition: LLVMBitCodes.h:214
@ FS_PERMODULE_CALLSITE_INFO
Definition: LLVMBitCodes.h:308
@ FS_PERMODULE_ALLOC_INFO
Definition: LLVMBitCodes.h:312
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
Definition: LLVMBitCodes.h:255
@ IDENTIFICATION_CODE_EPOCH
Definition: LLVMBitCodes.h:72
@ IDENTIFICATION_CODE_STRING
Definition: LLVMBitCodes.h:71
@ CST_CODE_BLOCKADDRESS
Definition: LLVMBitCodes.h:414
@ CST_CODE_NO_CFI_VALUE
Definition: LLVMBitCodes.h:425
@ CST_CODE_CE_SHUFVEC_EX
Definition: LLVMBitCodes.h:412
@ CST_CODE_CE_EXTRACTELT
Definition: LLVMBitCodes.h:406
@ CST_CODE_CE_SHUFFLEVEC
Definition: LLVMBitCodes.h:408
@ CST_CODE_WIDE_INTEGER
Definition: LLVMBitCodes.h:397
@ CST_CODE_DSO_LOCAL_EQUIVALENT
Definition: LLVMBitCodes.h:421
@ CST_CODE_AGGREGATE
Definition: LLVMBitCodes.h:399
@ CST_CODE_CE_INSERTELT
Definition: LLVMBitCodes.h:407
@ CST_CODE_CE_GEP_WITH_INRANGE
Definition: LLVMBitCodes.h:430
@ CST_CODE_INLINEASM
Definition: LLVMBitCodes.h:426
@ CALL_EXPLICIT_TYPE
Definition: LLVMBitCodes.h:578
@ COMDAT_SELECTION_KIND_LARGEST
Definition: LLVMBitCodes.h:796
@ COMDAT_SELECTION_KIND_ANY
Definition: LLVMBitCodes.h:794
@ COMDAT_SELECTION_KIND_SAME_SIZE
Definition: LLVMBitCodes.h:798
@ COMDAT_SELECTION_KIND_EXACT_MATCH
Definition: LLVMBitCodes.h:795
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
Definition: LLVMBitCodes.h:797
@ ATTR_KIND_STACK_PROTECT
Definition: LLVMBitCodes.h:715
@ ATTR_KIND_NO_UNWIND
Definition: LLVMBitCodes.h:707
@ ATTR_KIND_STACK_PROTECT_STRONG
Definition: LLVMBitCodes.h:717
@ ATTR_KIND_SANITIZE_MEMORY
Definition: LLVMBitCodes.h:721
@ ATTR_KIND_SAFESTACK
Definition: LLVMBitCodes.h:733
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
Definition: LLVMBitCodes.h:708
@ ATTR_KIND_SWIFT_ERROR
Definition: LLVMBitCodes.h:736
@ ATTR_KIND_STRUCT_RET
Definition: LLVMBitCodes.h:718
@ ATTR_KIND_MIN_SIZE
Definition: LLVMBitCodes.h:695
@ ATTR_KIND_NO_CALLBACK
Definition: LLVMBitCodes.h:760
@ ATTR_KIND_NO_CAPTURE
Definition: LLVMBitCodes.h:700
@ ATTR_KIND_FNRETTHUNK_EXTERN
Definition: LLVMBitCodes.h:773
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
Definition: LLVMBitCodes.h:789
@ ATTR_KIND_SANITIZE_ADDRESS
Definition: LLVMBitCodes.h:719
@ ATTR_KIND_NO_IMPLICIT_FLOAT
Definition: LLVMBitCodes.h:702
@ ATTR_KIND_NO_BUILTIN
Definition: LLVMBitCodes.h:699
@ ATTR_KIND_NO_RECURSE
Definition: LLVMBitCodes.h:737
@ ATTR_KIND_DEAD_ON_UNWIND
Definition: LLVMBitCodes.h:780
@ ATTR_KIND_CONVERGENT
Definition: LLVMBitCodes.h:732
@ ATTR_KIND_RETURNED
Definition: LLVMBitCodes.h:711
@ ATTR_KIND_STACK_ALIGNMENT
Definition: LLVMBitCodes.h:714
@ ATTR_KIND_SWIFT_SELF
Definition: LLVMBitCodes.h:735
@ ATTR_KIND_ALLOC_SIZE
Definition: LLVMBitCodes.h:740
@ ATTR_KIND_STACK_PROTECT_REQ
Definition: LLVMBitCodes.h:716
@ ATTR_KIND_INLINE_HINT
Definition: LLVMBitCodes.h:693
@ ATTR_KIND_NON_NULL
Definition: LLVMBitCodes.h:728
@ ATTR_KIND_NULL_POINTER_IS_VALID
Definition: LLVMBitCodes.h:756
@ ATTR_KIND_SANITIZE_HWADDRESS
Definition: LLVMBitCodes.h:744
@ ATTR_KIND_NO_RETURN
Definition: LLVMBitCodes.h:706
@ ATTR_KIND_MUSTPROGRESS
Definition: LLVMBitCodes.h:759
@ ATTR_KIND_RETURNS_TWICE
Definition: LLVMBitCodes.h:712
@ ATTR_KIND_SHADOWCALLSTACK
Definition: LLVMBitCodes.h:747
@ ATTR_KIND_OPT_FOR_FUZZING
Definition: LLVMBitCodes.h:746
@ ATTR_KIND_WRITABLE
Definition: LLVMBitCodes.h:778
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
Definition: LLVMBitCodes.h:782
@ ATTR_KIND_INITIALIZES
Definition: LLVMBitCodes.h:783
@ ATTR_KIND_ALLOCATED_POINTER
Definition: LLVMBitCodes.h:770
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
Definition: LLVMBitCodes.h:767
@ ATTR_KIND_SKIP_PROFILE
Definition: LLVMBitCodes.h:774
@ ATTR_KIND_ELEMENTTYPE
Definition: LLVMBitCodes.h:766
@ ATTR_KIND_CORO_ELIDE_SAFE
Definition: LLVMBitCodes.h:787
@ ATTR_KIND_ALLOC_KIND
Definition: LLVMBitCodes.h:771
@ ATTR_KIND_NO_MERGE
Definition: LLVMBitCodes.h:755
@ ATTR_KIND_STRICT_FP
Definition: LLVMBitCodes.h:743
@ ATTR_KIND_NO_DUPLICATE
Definition: LLVMBitCodes.h:701
@ ATTR_KIND_ALLOC_ALIGN
Definition: LLVMBitCodes.h:769
@ ATTR_KIND_NON_LAZY_BIND
Definition: LLVMBitCodes.h:704
@ ATTR_KIND_DEREFERENCEABLE
Definition: LLVMBitCodes.h:730
@ ATTR_KIND_READ_NONE
Definition: LLVMBitCodes.h:709
@ ATTR_KIND_UW_TABLE
Definition: LLVMBitCodes.h:722
@ ATTR_KIND_OPTIMIZE_NONE
Definition: LLVMBitCodes.h:726
@ ATTR_KIND_WRITEONLY
Definition: LLVMBitCodes.h:741
@ ATTR_KIND_HYBRID_PATCHABLE
Definition: LLVMBitCodes.h:784
@ ATTR_KIND_NO_RED_ZONE
Definition: LLVMBitCodes.h:705
@ ATTR_KIND_NOCF_CHECK
Definition: LLVMBitCodes.h:745
@ ATTR_KIND_NO_PROFILE
Definition: LLVMBitCodes.h:762
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
Definition: LLVMBitCodes.h:731
@ ATTR_KIND_SANITIZE_REALTIME
Definition: LLVMBitCodes.h:785
@ ATTR_KIND_IN_ALLOCA
Definition: LLVMBitCodes.h:727
@ ATTR_KIND_READ_ONLY
Definition: LLVMBitCodes.h:710
@ ATTR_KIND_ALIGNMENT
Definition: LLVMBitCodes.h:690
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
Definition: LLVMBitCodes.h:748
@ ATTR_KIND_ALWAYS_INLINE
Definition: LLVMBitCodes.h:691
@ ATTR_KIND_NOFPCLASS
Definition: LLVMBitCodes.h:776
@ ATTR_KIND_WILLRETURN
Definition: LLVMBitCodes.h:750
@ ATTR_KIND_SANITIZE_TYPE
Definition: LLVMBitCodes.h:790
@ ATTR_KIND_PRESPLIT_COROUTINE
Definition: LLVMBitCodes.h:772
@ ATTR_KIND_NO_ALIAS
Definition: LLVMBitCodes.h:698
@ ATTR_KIND_VSCALE_RANGE
Definition: LLVMBitCodes.h:763
@ ATTR_KIND_NO_SANITIZE_COVERAGE
Definition: LLVMBitCodes.h:765
@ ATTR_KIND_JUMP_TABLE
Definition: LLVMBitCodes.h:729
@ ATTR_KIND_SPECULATABLE
Definition: LLVMBitCodes.h:742
@ ATTR_KIND_NO_INLINE
Definition: LLVMBitCodes.h:703
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
Definition: LLVMBitCodes.h:786
@ ATTR_KIND_NO_SANITIZE_BOUNDS
Definition: LLVMBitCodes.h:768
@ ATTR_KIND_SANITIZE_MEMTAG
Definition: LLVMBitCodes.h:753
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
Definition: LLVMBitCodes.h:779
@ ATTR_KIND_SANITIZE_THREAD
Definition: LLVMBitCodes.h:720
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
Definition: LLVMBitCodes.h:777
@ ATTR_KIND_PREALLOCATED
Definition: LLVMBitCodes.h:754
@ ATTR_KIND_SWIFT_ASYNC
Definition: LLVMBitCodes.h:764
@ OBO_NO_SIGNED_WRAP
Definition: LLVMBitCodes.h:512
@ OBO_NO_UNSIGNED_WRAP
Definition: LLVMBitCodes.h:511
@ TIO_NO_UNSIGNED_WRAP
Definition: LLVMBitCodes.h:518
@ TIO_NO_SIGNED_WRAP
Definition: LLVMBitCodes.h:519
@ USELIST_CODE_DEFAULT
Definition: LLVMBitCodes.h:684
@ SYNC_SCOPE_NAMES_BLOCK_ID
Definition: LLVMBitCodes.h:65
@ PARAMATTR_BLOCK_ID
Definition: LLVMBitCodes.h:33
@ TYPE_BLOCK_ID_NEW
Definition: LLVMBitCodes.h:48
@ CONSTANTS_BLOCK_ID
Definition: LLVMBitCodes.h:36
@ PARAMATTR_GROUP_BLOCK_ID
Definition: LLVMBitCodes.h:34
@ METADATA_KIND_BLOCK_ID
Definition: LLVMBitCodes.h:57
@ IDENTIFICATION_BLOCK_ID
Definition: LLVMBitCodes.h:42
@ GLOBALVAL_SUMMARY_BLOCK_ID
Definition: LLVMBitCodes.h:53
@ METADATA_ATTACHMENT_ID
Definition: LLVMBitCodes.h:46
@ METADATA_BLOCK_ID
Definition: LLVMBitCodes.h:45
@ FUNCTION_BLOCK_ID
Definition: LLVMBitCodes.h:37
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
Definition: LLVMBitCodes.h:61
@ MODULE_STRTAB_BLOCK_ID
Definition: LLVMBitCodes.h:52
@ VALUE_SYMTAB_BLOCK_ID
Definition: LLVMBitCodes.h:44
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
Definition: LLVMBitCodes.h:55
@ USELIST_BLOCK_ID
Definition: LLVMBitCodes.h:50
@ CAST_ADDRSPACECAST
Definition: LLVMBitCodes.h:452
@ MODULE_CODE_FUNCTION
Definition: LLVMBitCodes.h:100
@ MODULE_CODE_VERSION
Definition: LLVMBitCodes.h:85
@ MODULE_CODE_SOURCE_FILENAME
Definition: LLVMBitCodes.h:116
@ MODULE_CODE_SECTIONNAME
Definition: LLVMBitCodes.h:89
@ MODULE_CODE_TRIPLE
Definition: LLVMBitCodes.h:86
@ MODULE_CODE_DATALAYOUT
Definition: LLVMBitCodes.h:87
@ MODULE_CODE_GLOBALVAR
Definition: LLVMBitCodes.h:96
@ MODULE_CODE_VSTOFFSET
Definition: LLVMBitCodes.h:108
@ MODULE_CODE_GCNAME
Definition: LLVMBitCodes.h:105
@ MODULE_CODE_COMDAT
Definition: LLVMBitCodes.h:106
@ FUNC_CODE_INST_CATCHRET
Definition: LLVMBitCodes.h:654
@ FUNC_CODE_INST_LANDINGPAD
Definition: LLVMBitCodes.h:652
@ FUNC_CODE_INST_EXTRACTVAL
Definition: LLVMBitCodes.h:617
@ FUNC_CODE_INST_CATCHPAD
Definition: LLVMBitCodes.h:655
@ FUNC_CODE_INST_RESUME
Definition: LLVMBitCodes.h:639
@ FUNC_CODE_INST_CMP2
Definition: LLVMBitCodes.h:621
@ FUNC_CODE_INST_FENCE
Definition: LLVMBitCodes.h:632
@ FUNC_CODE_INST_CALLBR
Definition: LLVMBitCodes.h:663
@ FUNC_CODE_INST_CATCHSWITCH
Definition: LLVMBitCodes.h:657
@ FUNC_CODE_INST_VSELECT
Definition: LLVMBitCodes.h:623
@ FUNC_CODE_INST_GEP
Definition: LLVMBitCodes.h:646
@ FUNC_CODE_INST_CLEANUPRET
Definition: LLVMBitCodes.h:653
@ FUNC_CODE_DEBUG_RECORD_VALUE
Definition: LLVMBitCodes.h:671
@ FUNC_CODE_INST_LOADATOMIC
Definition: LLVMBitCodes.h:642
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
Definition: LLVMBitCodes.h:675
@ FUNC_CODE_INST_LOAD
Definition: LLVMBitCodes.h:608
@ FUNC_CODE_INST_STOREATOMIC
Definition: LLVMBitCodes.h:648
@ FUNC_CODE_INST_ATOMICRMW
Definition: LLVMBitCodes.h:666
@ FUNC_CODE_INST_BINOP
Definition: LLVMBitCodes.h:588
@ FUNC_CODE_INST_STORE
Definition: LLVMBitCodes.h:647
@ FUNC_CODE_DEBUG_LOC_AGAIN
Definition: LLVMBitCodes.h:627
@ FUNC_CODE_INST_EXTRACTELT
Definition: LLVMBitCodes.h:592
@ FUNC_CODE_INST_INDIRECTBR
Definition: LLVMBitCodes.h:625
@ FUNC_CODE_INST_INVOKE
Definition: LLVMBitCodes.h:600
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
Definition: LLVMBitCodes.h:678
@ FUNC_CODE_INST_INSERTVAL
Definition: LLVMBitCodes.h:618
@ FUNC_CODE_DECLAREBLOCKS
Definition: LLVMBitCodes.h:586
@ FUNC_CODE_DEBUG_RECORD_LABEL
Definition: LLVMBitCodes.h:680
@ FUNC_CODE_INST_SWITCH
Definition: LLVMBitCodes.h:599
@ FUNC_CODE_INST_PHI
Definition: LLVMBitCodes.h:604
@ FUNC_CODE_INST_RET
Definition: LLVMBitCodes.h:597
@ FUNC_CODE_INST_CALL
Definition: LLVMBitCodes.h:629
@ FUNC_CODE_INST_ALLOCA
Definition: LLVMBitCodes.h:607
@ FUNC_CODE_INST_INSERTELT
Definition: LLVMBitCodes.h:593
@ FUNC_CODE_BLOCKADDR_USERS
Definition: LLVMBitCodes.h:669
@ FUNC_CODE_INST_CLEANUPPAD
Definition: LLVMBitCodes.h:656
@ FUNC_CODE_INST_SHUFFLEVEC
Definition: LLVMBitCodes.h:594
@ FUNC_CODE_INST_UNOP
Definition: LLVMBitCodes.h:662
@ FUNC_CODE_INST_VAARG
Definition: LLVMBitCodes.h:611
@ FUNC_CODE_INST_FREEZE
Definition: LLVMBitCodes.h:665
@ FUNC_CODE_INST_CMPXCHG
Definition: LLVMBitCodes.h:649
@ FUNC_CODE_INST_UNREACHABLE
Definition: LLVMBitCodes.h:602
@ FUNC_CODE_INST_CAST
Definition: LLVMBitCodes.h:589
@ FUNC_CODE_DEBUG_LOC
Definition: LLVMBitCodes.h:631
@ FUNC_CODE_DEBUG_RECORD_DECLARE
Definition: LLVMBitCodes.h:673
@ FUNC_CODE_OPERAND_BUNDLE
Definition: LLVMBitCodes.h:661
@ FIRST_APPLICATION_ABBREV
Definition: BitCodeEnums.h:60
@ OPERAND_BUNDLE_TAG
Definition: LLVMBitCodes.h:183
@ PARAMATTR_GRP_CODE_ENTRY
Definition: LLVMBitCodes.h:131
@ PARAMATTR_CODE_ENTRY
Definition: LLVMBitCodes.h:130
@ ORDERING_NOTATOMIC
Definition: LLVMBitCodes.h:564
@ ORDERING_UNORDERED
Definition: LLVMBitCodes.h:565
@ ORDERING_MONOTONIC
Definition: LLVMBitCodes.h:566
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
Error build(ArrayRef< Module * > Mods, SmallVector< char, 0 > &Symtab, StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc)
Fills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
Definition: IRSymtab.cpp:378
template llvm::DenseMap< LinearFrameId, FrameStat > computeFrameHistogram< LinearFrameId >(llvm::MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &MemProfCallStackData)
uint32_t LinearFrameId
Definition: MemProf.h:215
NodeAddr< CodeNode * > Code
Definition: RDFGraph.h:388
void write32le(void *P, uint32_t V)
Definition: Endian.h:468
uint32_t read32be(const void *P)
Definition: Endian.h:434
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition: MathExtras.h:353
unsigned encode(MaybeAlign A)
Returns a representation of the alignment that encodes undefined as 0.
Definition: Alignment.h:217
@ Write
Definition: CodeGenData.h:108
void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition: STLExtras.h:2448
void writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the given raw output...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
@ BWH_HeaderSize
Definition: BitCodeEnums.h:32
FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2115
void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
void embedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedCmdline, const std::vector< uint8_t > &CmdArgs)
If EmbedBitcode is set, save a copy of the llvm IR as data in the __LLVM,__bitcode section (....
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1746
Error write(MCStreamer &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue)
Definition: DWP.cpp:625
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1664
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
AtomicOrdering
Atomic ordering for LLVM's memory model.
std::unordered_set< GlobalValueSummary * > GVSummaryPtrSet
A set of global value summary pointers.
DWARFExpression::Operation Op
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1841
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:217
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
bool isBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcode - Return true if the given bytes are the magic bytes for LLVM IR bitcode,...
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1069
GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition: Module.cpp:865
#define N
#define NC
Definition: regutils.h:42
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
Class to accumulate and hold information about a callee.
static constexpr unsigned RelBlockFreqBits
The value stored in RelBlockFreq has to be interpreted as the digits of a scaled number with a scale ...
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117
static const Target * lookupTarget(StringRef Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Structure to hold a use-list order.
Definition: UseListOrder.h:26
ValID - Represents a reference of a definition of some sort with no type.
Definition: LLParser.h:53
Struct that holds a reference to a particular GUID in a global value summary.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...