LLVM 19.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"
66#include "llvm/Support/Endian.h"
67#include "llvm/Support/Error.h"
70#include "llvm/Support/SHA1.h"
73#include <algorithm>
74#include <cassert>
75#include <cstddef>
76#include <cstdint>
77#include <iterator>
78#include <map>
79#include <memory>
80#include <optional>
81#include <string>
82#include <utility>
83#include <vector>
84
85using namespace llvm;
86
88 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
89 cl::desc("Number of metadatas above which we emit an index "
90 "to enable lazy-loading"));
92 "bitcode-flush-threshold", cl::Hidden, cl::init(512),
93 cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
94
96 "write-relbf-to-summary", cl::Hidden, cl::init(false),
97 cl::desc("Write relative block frequency to function summary "));
98
99namespace llvm {
101}
102
105
106namespace {
107
108/// These are manifest constants used by the bitcode writer. They do not need to
109/// be kept in sync with the reader, but need to be consistent within this file.
110enum {
111 // VALUE_SYMTAB_BLOCK abbrev id's.
112 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
113 VST_ENTRY_7_ABBREV,
114 VST_ENTRY_6_ABBREV,
115 VST_BBENTRY_6_ABBREV,
116
117 // CONSTANTS_BLOCK abbrev id's.
118 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
119 CONSTANTS_INTEGER_ABBREV,
120 CONSTANTS_CE_CAST_Abbrev,
121 CONSTANTS_NULL_Abbrev,
122
123 // FUNCTION_BLOCK abbrev id's.
124 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
125 FUNCTION_INST_UNOP_ABBREV,
126 FUNCTION_INST_UNOP_FLAGS_ABBREV,
127 FUNCTION_INST_BINOP_ABBREV,
128 FUNCTION_INST_BINOP_FLAGS_ABBREV,
129 FUNCTION_INST_CAST_ABBREV,
130 FUNCTION_INST_CAST_FLAGS_ABBREV,
131 FUNCTION_INST_RET_VOID_ABBREV,
132 FUNCTION_INST_RET_VAL_ABBREV,
133 FUNCTION_INST_UNREACHABLE_ABBREV,
134 FUNCTION_INST_GEP_ABBREV,
135 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
136};
137
138/// Abstract class to manage the bitcode writing, subclassed for each bitcode
139/// file type.
140class BitcodeWriterBase {
141protected:
142 /// The stream created and owned by the client.
143 BitstreamWriter &Stream;
144
145 StringTableBuilder &StrtabBuilder;
146
147public:
148 /// Constructs a BitcodeWriterBase object that writes to the provided
149 /// \p Stream.
150 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
151 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
152
153protected:
154 void writeModuleVersion();
155};
156
157void BitcodeWriterBase::writeModuleVersion() {
158 // VERSION: [version#]
159 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
160}
161
162/// Base class to manage the module bitcode writing, currently subclassed for
163/// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
164class ModuleBitcodeWriterBase : public BitcodeWriterBase {
165protected:
166 /// The Module to write to bitcode.
167 const Module &M;
168
169 /// Enumerates ids for all values in the module.
171
172 /// Optional per-module index to write for ThinLTO.
174
175 /// Map that holds the correspondence between GUIDs in the summary index,
176 /// that came from indirect call profiles, and a value id generated by this
177 /// class to use in the VST and summary block records.
178 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
179
180 /// Tracks the last value id recorded in the GUIDToValueMap.
181 unsigned GlobalValueId;
182
183 /// Saves the offset of the VSTOffset record that must eventually be
184 /// backpatched with the offset of the actual VST.
185 uint64_t VSTOffsetPlaceholder = 0;
186
187public:
188 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
189 /// writing to the provided \p Buffer.
190 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
191 BitstreamWriter &Stream,
192 bool ShouldPreserveUseListOrder,
194 : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
195 VE(M, ShouldPreserveUseListOrder), Index(Index) {
196 // Assign ValueIds to any callee values in the index that came from
197 // indirect call profiles and were recorded as a GUID not a Value*
198 // (which would have been assigned an ID by the ValueEnumerator).
199 // The starting ValueId is just after the number of values in the
200 // ValueEnumerator, so that they can be emitted in the VST.
201 GlobalValueId = VE.getValues().size();
202 if (!Index)
203 return;
204 for (const auto &GUIDSummaryLists : *Index)
205 // Examine all summaries for this GUID.
206 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
207 if (auto FS = dyn_cast<FunctionSummary>(Summary.get())) {
208 // For each call in the function summary, see if the call
209 // is to a GUID (which means it is for an indirect call,
210 // otherwise we would have a Value for it). If so, synthesize
211 // a value id.
212 for (auto &CallEdge : FS->calls())
213 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
214 assignValueId(CallEdge.first.getGUID());
215
216 // For each referenced variables in the function summary, see if the
217 // variable is represented by a GUID (as opposed to a symbol to
218 // declarations or definitions in the module). If so, synthesize a
219 // value id.
220 for (auto &RefEdge : FS->refs())
221 if (!RefEdge.haveGVs() || !RefEdge.getValue())
222 assignValueId(RefEdge.getGUID());
223 }
224 }
225
226protected:
227 void writePerModuleGlobalValueSummary();
228
229private:
230 void writePerModuleFunctionSummaryRecord(
232 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
233 unsigned CallsiteAbbrev, unsigned AllocAbbrev, const Function &F);
234 void writeModuleLevelReferences(const GlobalVariable &V,
236 unsigned FSModRefsAbbrev,
237 unsigned FSModVTableRefsAbbrev);
238
239 void assignValueId(GlobalValue::GUID ValGUID) {
240 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
241 }
242
243 unsigned getValueId(GlobalValue::GUID ValGUID) {
244 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
245 // Expect that any GUID value had a value Id assigned by an
246 // earlier call to assignValueId.
247 assert(VMI != GUIDToValueIdMap.end() &&
248 "GUID does not have assigned value Id");
249 return VMI->second;
250 }
251
252 // Helper to get the valueId for the type of value recorded in VI.
253 unsigned getValueId(ValueInfo VI) {
254 if (!VI.haveGVs() || !VI.getValue())
255 return getValueId(VI.getGUID());
256 return VE.getValueID(VI.getValue());
257 }
258
259 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
260};
261
262/// Class to manage the bitcode writing for a module.
263class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
264 /// True if a module hash record should be written.
265 bool GenerateHash;
266
267 /// If non-null, when GenerateHash is true, the resulting hash is written
268 /// into ModHash.
269 ModuleHash *ModHash;
270
271 SHA1 Hasher;
272
273 /// The start bit of the identification block.
274 uint64_t BitcodeStartBit;
275
276public:
277 /// Constructs a ModuleBitcodeWriter object for the given Module,
278 /// writing to the provided \p Buffer.
279 ModuleBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
280 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
281 const ModuleSummaryIndex *Index, bool GenerateHash,
282 ModuleHash *ModHash = nullptr)
283 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
284 ShouldPreserveUseListOrder, Index),
285 GenerateHash(GenerateHash), ModHash(ModHash),
286 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
287
288 /// Emit the current module to the bitstream.
289 void write();
290
291private:
292 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
293
294 size_t addToStrtab(StringRef Str);
295
296 void writeAttributeGroupTable();
297 void writeAttributeTable();
298 void writeTypeTable();
299 void writeComdats();
300 void writeValueSymbolTableForwardDecl();
301 void writeModuleInfo();
302 void writeValueAsMetadata(const ValueAsMetadata *MD,
305 unsigned Abbrev);
306 unsigned createDILocationAbbrev();
308 unsigned &Abbrev);
309 unsigned createGenericDINodeAbbrev();
311 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
313 unsigned Abbrev);
316 unsigned Abbrev);
317 void writeDIEnumerator(const DIEnumerator *N,
318 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
320 unsigned Abbrev);
321 void writeDIStringType(const DIStringType *N,
322 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
324 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
326 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
329 unsigned Abbrev);
331 unsigned Abbrev);
333 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
334 void writeDISubprogram(const DISubprogram *N,
335 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
337 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
340 unsigned Abbrev);
342 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
344 unsigned Abbrev);
346 unsigned Abbrev);
348 unsigned Abbrev);
351 unsigned Abbrev);
353 unsigned Abbrev);
356 unsigned Abbrev);
359 unsigned Abbrev);
362 unsigned Abbrev);
364 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
365 void writeDILabel(const DILabel *N,
366 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
367 void writeDIExpression(const DIExpression *N,
368 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
371 unsigned Abbrev);
373 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
376 unsigned Abbrev);
377 unsigned createNamedMetadataAbbrev();
378 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
379 unsigned createMetadataStringsAbbrev();
380 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
382 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
384 std::vector<unsigned> *MDAbbrevs = nullptr,
385 std::vector<uint64_t> *IndexPos = nullptr);
386 void writeModuleMetadata();
387 void writeFunctionMetadata(const Function &F);
388 void writeFunctionMetadataAttachment(const Function &F);
389 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
390 const GlobalObject &GO);
391 void writeModuleMetadataKinds();
392 void writeOperandBundleTags();
393 void writeSyncScopeNames();
394 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
395 void writeModuleConstants();
396 bool pushValueAndType(const Value *V, unsigned InstID,
398 void writeOperandBundles(const CallBase &CB, unsigned InstID);
399 void pushValue(const Value *V, unsigned InstID,
401 void pushValueSigned(const Value *V, unsigned InstID,
403 void writeInstruction(const Instruction &I, unsigned InstID,
405 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
406 void writeGlobalValueSymbolTable(
407 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
408 void writeUseList(UseListOrder &&Order);
409 void writeUseListBlock(const Function *F);
410 void
411 writeFunction(const Function &F,
412 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
413 void writeBlockInfo();
414 void writeModuleHash(StringRef View);
415
416 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
417 return unsigned(SSID);
418 }
419
420 unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
421};
422
423/// Class to manage the bitcode writing for a combined index.
424class IndexBitcodeWriter : public BitcodeWriterBase {
425 /// The combined index to write to bitcode.
427
428 /// When writing a subset of the index for distributed backends, client
429 /// provides a map of modules to the corresponding GUIDs/summaries to write.
430 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
431
432 /// Map that holds the correspondence between the GUID used in the combined
433 /// index and a value id generated by this class to use in references.
434 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
435
436 // The stack ids used by this index, which will be a subset of those in
437 // the full index in the case of distributed indexes.
438 std::vector<uint64_t> StackIds;
439
440 // Keep a map of the stack id indices used by records being written for this
441 // index to the index of the corresponding stack id in the above StackIds
442 // vector. Ensures we write each referenced stack id once.
443 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
444
445 /// Tracks the last value id recorded in the GUIDToValueMap.
446 unsigned GlobalValueId = 0;
447
448 /// Tracks the assignment of module paths in the module path string table to
449 /// an id assigned for use in summary references to the module path.
451
452public:
453 /// Constructs a IndexBitcodeWriter object for the given combined index,
454 /// writing to the provided \p Buffer. When writing a subset of the index
455 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
456 IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
458 const std::map<std::string, GVSummaryMapTy>
459 *ModuleToSummariesForIndex = nullptr)
460 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
461 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
462
463 // See if the StackIdIndex was already added to the StackId map and
464 // vector. If not, record it.
465 auto RecordStackIdReference = [&](unsigned StackIdIndex) {
466 // If the StackIdIndex is not yet in the map, the below insert ensures
467 // that it will point to the new StackIds vector entry we push to just
468 // below.
469 auto Inserted =
470 StackIdIndicesToIndex.insert({StackIdIndex, StackIds.size()});
471 if (Inserted.second)
472 StackIds.push_back(Index.getStackIdAtIndex(StackIdIndex));
473 };
474
475 // Assign unique value ids to all summaries to be written, for use
476 // in writing out the call graph edges. Save the mapping from GUID
477 // to the new global value id to use when writing those edges, which
478 // are currently saved in the index in terms of GUID.
479 forEachSummary([&](GVInfo I, bool IsAliasee) {
480 GUIDToValueIdMap[I.first] = ++GlobalValueId;
481 if (IsAliasee)
482 return;
483 auto *FS = dyn_cast<FunctionSummary>(I.second);
484 if (!FS)
485 return;
486 // Record all stack id indices actually used in the summary entries being
487 // written, so that we can compact them in the case of distributed ThinLTO
488 // indexes.
489 for (auto &CI : FS->callsites()) {
490 // If the stack id list is empty, this callsite info was synthesized for
491 // a missing tail call frame. Ensure that the callee's GUID gets a value
492 // id. Normally we only generate these for defined summaries, which in
493 // the case of distributed ThinLTO is only the functions already defined
494 // in the module or that we want to import. We don't bother to include
495 // all the callee symbols as they aren't normally needed in the backend.
496 // However, for the synthesized callsite infos we do need the callee
497 // GUID in the backend so that we can correlate the identified callee
498 // with this callsite info (which for non-tail calls is done by the
499 // ordering of the callsite infos and verified via stack ids).
500 if (CI.StackIdIndices.empty()) {
501 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
502 continue;
503 }
504 for (auto Idx : CI.StackIdIndices)
505 RecordStackIdReference(Idx);
506 }
507 for (auto &AI : FS->allocs())
508 for (auto &MIB : AI.MIBs)
509 for (auto Idx : MIB.StackIdIndices)
510 RecordStackIdReference(Idx);
511 });
512 }
513
514 /// The below iterator returns the GUID and associated summary.
515 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
516
517 /// Calls the callback for each value GUID and summary to be written to
518 /// bitcode. This hides the details of whether they are being pulled from the
519 /// entire index or just those in a provided ModuleToSummariesForIndex map.
520 template<typename Functor>
521 void forEachSummary(Functor Callback) {
522 if (ModuleToSummariesForIndex) {
523 for (auto &M : *ModuleToSummariesForIndex)
524 for (auto &Summary : M.second) {
525 Callback(Summary, false);
526 // Ensure aliasee is handled, e.g. for assigning a valueId,
527 // even if we are not importing the aliasee directly (the
528 // imported alias will contain a copy of aliasee).
529 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
530 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
531 }
532 } else {
533 for (auto &Summaries : Index)
534 for (auto &Summary : Summaries.second.SummaryList)
535 Callback({Summaries.first, Summary.get()}, false);
536 }
537 }
538
539 /// Calls the callback for each entry in the modulePaths StringMap that
540 /// should be written to the module path string table. This hides the details
541 /// of whether they are being pulled from the entire index or just those in a
542 /// provided ModuleToSummariesForIndex map.
543 template <typename Functor> void forEachModule(Functor Callback) {
544 if (ModuleToSummariesForIndex) {
545 for (const auto &M : *ModuleToSummariesForIndex) {
546 const auto &MPI = Index.modulePaths().find(M.first);
547 if (MPI == Index.modulePaths().end()) {
548 // This should only happen if the bitcode file was empty, in which
549 // case we shouldn't be importing (the ModuleToSummariesForIndex
550 // would only include the module we are writing and index for).
551 assert(ModuleToSummariesForIndex->size() == 1);
552 continue;
553 }
554 Callback(*MPI);
555 }
556 } else {
557 // Since StringMap iteration order isn't guaranteed, order by path string
558 // first.
559 // FIXME: Make this a vector of StringMapEntry instead to avoid the later
560 // map lookup.
561 std::vector<StringRef> ModulePaths;
562 for (auto &[ModPath, _] : Index.modulePaths())
563 ModulePaths.push_back(ModPath);
564 llvm::sort(ModulePaths.begin(), ModulePaths.end());
565 for (auto &ModPath : ModulePaths)
566 Callback(*Index.modulePaths().find(ModPath));
567 }
568 }
569
570 /// Main entry point for writing a combined index to bitcode.
571 void write();
572
573private:
574 void writeModStrings();
575 void writeCombinedGlobalValueSummary();
576
577 std::optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
578 auto VMI = GUIDToValueIdMap.find(ValGUID);
579 if (VMI == GUIDToValueIdMap.end())
580 return std::nullopt;
581 return VMI->second;
582 }
583
584 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
585};
586
587} // end anonymous namespace
588
589static unsigned getEncodedCastOpcode(unsigned Opcode) {
590 switch (Opcode) {
591 default: llvm_unreachable("Unknown cast instruction!");
592 case Instruction::Trunc : return bitc::CAST_TRUNC;
593 case Instruction::ZExt : return bitc::CAST_ZEXT;
594 case Instruction::SExt : return bitc::CAST_SEXT;
595 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
596 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
597 case Instruction::UIToFP : return bitc::CAST_UITOFP;
598 case Instruction::SIToFP : return bitc::CAST_SITOFP;
599 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
600 case Instruction::FPExt : return bitc::CAST_FPEXT;
601 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
602 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
603 case Instruction::BitCast : return bitc::CAST_BITCAST;
604 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
605 }
606}
607
608static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
609 switch (Opcode) {
610 default: llvm_unreachable("Unknown binary instruction!");
611 case Instruction::FNeg: return bitc::UNOP_FNEG;
612 }
613}
614
615static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
616 switch (Opcode) {
617 default: llvm_unreachable("Unknown binary instruction!");
618 case Instruction::Add:
619 case Instruction::FAdd: return bitc::BINOP_ADD;
620 case Instruction::Sub:
621 case Instruction::FSub: return bitc::BINOP_SUB;
622 case Instruction::Mul:
623 case Instruction::FMul: return bitc::BINOP_MUL;
624 case Instruction::UDiv: return bitc::BINOP_UDIV;
625 case Instruction::FDiv:
626 case Instruction::SDiv: return bitc::BINOP_SDIV;
627 case Instruction::URem: return bitc::BINOP_UREM;
628 case Instruction::FRem:
629 case Instruction::SRem: return bitc::BINOP_SREM;
630 case Instruction::Shl: return bitc::BINOP_SHL;
631 case Instruction::LShr: return bitc::BINOP_LSHR;
632 case Instruction::AShr: return bitc::BINOP_ASHR;
633 case Instruction::And: return bitc::BINOP_AND;
634 case Instruction::Or: return bitc::BINOP_OR;
635 case Instruction::Xor: return bitc::BINOP_XOR;
636 }
637}
638
640 switch (Op) {
641 default: llvm_unreachable("Unknown RMW operation!");
647 case AtomicRMWInst::Or: return bitc::RMW_OR;
658 return bitc::RMW_UINC_WRAP;
660 return bitc::RMW_UDEC_WRAP;
661 }
662}
663
664static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
665 switch (Ordering) {
666 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
667 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
668 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
669 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
670 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
671 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
672 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
673 }
674 llvm_unreachable("Invalid ordering");
675}
676
677static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
678 StringRef Str, unsigned AbbrevToUse) {
680
681 // Code: [strchar x N]
682 for (char C : Str) {
683 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
684 AbbrevToUse = 0;
685 Vals.push_back(C);
686 }
687
688 // Emit the finished record.
689 Stream.EmitRecord(Code, Vals, AbbrevToUse);
690}
691
693 switch (Kind) {
694 case Attribute::Alignment:
696 case Attribute::AllocAlign:
698 case Attribute::AllocSize:
700 case Attribute::AlwaysInline:
702 case Attribute::Builtin:
704 case Attribute::ByVal:
706 case Attribute::Convergent:
708 case Attribute::InAlloca:
710 case Attribute::Cold:
712 case Attribute::DisableSanitizerInstrumentation:
714 case Attribute::FnRetThunkExtern:
716 case Attribute::Hot:
717 return bitc::ATTR_KIND_HOT;
718 case Attribute::ElementType:
720 case Attribute::InlineHint:
722 case Attribute::InReg:
724 case Attribute::JumpTable:
726 case Attribute::MinSize:
728 case Attribute::AllocatedPointer:
730 case Attribute::AllocKind:
732 case Attribute::Memory:
734 case Attribute::NoFPClass:
736 case Attribute::Naked:
738 case Attribute::Nest:
740 case Attribute::NoAlias:
742 case Attribute::NoBuiltin:
744 case Attribute::NoCallback:
746 case Attribute::NoCapture:
748 case Attribute::NoDuplicate:
750 case Attribute::NoFree:
752 case Attribute::NoImplicitFloat:
754 case Attribute::NoInline:
756 case Attribute::NoRecurse:
758 case Attribute::NoMerge:
760 case Attribute::NonLazyBind:
762 case Attribute::NonNull:
764 case Attribute::Dereferenceable:
766 case Attribute::DereferenceableOrNull:
768 case Attribute::NoRedZone:
770 case Attribute::NoReturn:
772 case Attribute::NoSync:
774 case Attribute::NoCfCheck:
776 case Attribute::NoProfile:
778 case Attribute::SkipProfile:
780 case Attribute::NoUnwind:
782 case Attribute::NoSanitizeBounds:
784 case Attribute::NoSanitizeCoverage:
786 case Attribute::NullPointerIsValid:
788 case Attribute::OptimizeForDebugging:
790 case Attribute::OptForFuzzing:
792 case Attribute::OptimizeForSize:
794 case Attribute::OptimizeNone:
796 case Attribute::ReadNone:
798 case Attribute::ReadOnly:
800 case Attribute::Returned:
802 case Attribute::ReturnsTwice:
804 case Attribute::SExt:
806 case Attribute::Speculatable:
808 case Attribute::StackAlignment:
810 case Attribute::StackProtect:
812 case Attribute::StackProtectReq:
814 case Attribute::StackProtectStrong:
816 case Attribute::SafeStack:
818 case Attribute::ShadowCallStack:
820 case Attribute::StrictFP:
822 case Attribute::StructRet:
824 case Attribute::SanitizeAddress:
826 case Attribute::SanitizeHWAddress:
828 case Attribute::SanitizeThread:
830 case Attribute::SanitizeMemory:
832 case Attribute::SanitizeNumericalStability:
834 case Attribute::SpeculativeLoadHardening:
836 case Attribute::SwiftError:
838 case Attribute::SwiftSelf:
840 case Attribute::SwiftAsync:
842 case Attribute::UWTable:
844 case Attribute::VScaleRange:
846 case Attribute::WillReturn:
848 case Attribute::WriteOnly:
850 case Attribute::ZExt:
852 case Attribute::ImmArg:
854 case Attribute::SanitizeMemTag:
856 case Attribute::Preallocated:
858 case Attribute::NoUndef:
860 case Attribute::ByRef:
862 case Attribute::MustProgress:
864 case Attribute::PresplitCoroutine:
866 case Attribute::Writable:
868 case Attribute::CoroDestroyOnlyWhenComplete:
870 case Attribute::DeadOnUnwind:
872 case Attribute::Range:
874 case Attribute::Initializes:
877 llvm_unreachable("Can not encode end-attribute kinds marker.");
878 case Attribute::None:
879 llvm_unreachable("Can not encode none-attribute.");
882 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
883 }
884
885 llvm_unreachable("Trying to encode unknown attribute");
886}
887
889 if ((int64_t)V >= 0)
890 Vals.push_back(V << 1);
891 else
892 Vals.push_back((-V << 1) | 1);
893}
894
895static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {
896 // We have an arbitrary precision integer value to write whose
897 // bit width is > 64. However, in canonical unsigned integer
898 // format it is likely that the high bits are going to be zero.
899 // So, we only write the number of active words.
900 unsigned NumWords = A.getActiveWords();
901 const uint64_t *RawData = A.getRawData();
902 for (unsigned i = 0; i < NumWords; i++)
903 emitSignedInt64(Vals, RawData[i]);
904}
905
907 const ConstantRange &CR, bool EmitBitWidth) {
908 unsigned BitWidth = CR.getBitWidth();
909 if (EmitBitWidth)
910 Record.push_back(BitWidth);
911 if (BitWidth > 64) {
912 Record.push_back(CR.getLower().getActiveWords() |
913 (uint64_t(CR.getUpper().getActiveWords()) << 32));
916 } else {
919 }
920}
921
922void ModuleBitcodeWriter::writeAttributeGroupTable() {
923 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
925 if (AttrGrps.empty()) return;
926
928
930 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
931 unsigned AttrListIndex = Pair.first;
932 AttributeSet AS = Pair.second;
933 Record.push_back(VE.getAttributeGroupID(Pair));
934 Record.push_back(AttrListIndex);
935
936 for (Attribute Attr : AS) {
937 if (Attr.isEnumAttribute()) {
938 Record.push_back(0);
939 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
940 } else if (Attr.isIntAttribute()) {
941 Record.push_back(1);
942 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
943 Record.push_back(Attr.getValueAsInt());
944 } else if (Attr.isStringAttribute()) {
945 StringRef Kind = Attr.getKindAsString();
946 StringRef Val = Attr.getValueAsString();
947
948 Record.push_back(Val.empty() ? 3 : 4);
949 Record.append(Kind.begin(), Kind.end());
950 Record.push_back(0);
951 if (!Val.empty()) {
952 Record.append(Val.begin(), Val.end());
953 Record.push_back(0);
954 }
955 } else if (Attr.isTypeAttribute()) {
956 Type *Ty = Attr.getValueAsType();
957 Record.push_back(Ty ? 6 : 5);
958 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
959 if (Ty)
960 Record.push_back(VE.getTypeID(Attr.getValueAsType()));
961 } else if (Attr.isConstantRangeAttribute()) {
962 Record.push_back(7);
963 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
964 emitConstantRange(Record, Attr.getValueAsConstantRange(),
965 /*EmitBitWidth=*/true);
966 } else {
967 assert(Attr.isConstantRangeListAttribute());
968 Record.push_back(8);
969 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
970 ArrayRef<ConstantRange> Val = Attr.getValueAsConstantRangeList();
971 Record.push_back(Val.size());
972 Record.push_back(Val[0].getBitWidth());
973 for (auto &CR : Val)
974 emitConstantRange(Record, CR, /*EmitBitWidth=*/false);
975 }
976 }
977
979 Record.clear();
980 }
981
982 Stream.ExitBlock();
983}
984
985void ModuleBitcodeWriter::writeAttributeTable() {
986 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
987 if (Attrs.empty()) return;
988
990
992 for (const AttributeList &AL : Attrs) {
993 for (unsigned i : AL.indexes()) {
994 AttributeSet AS = AL.getAttributes(i);
995 if (AS.hasAttributes())
996 Record.push_back(VE.getAttributeGroupID({i, AS}));
997 }
998
1000 Record.clear();
1001 }
1002
1003 Stream.ExitBlock();
1004}
1005
1006/// WriteTypeTable - Write out the type table for a module.
1007void ModuleBitcodeWriter::writeTypeTable() {
1008 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
1009
1010 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
1012
1014
1015 // Abbrev for TYPE_CODE_OPAQUE_POINTER.
1016 auto Abbv = std::make_shared<BitCodeAbbrev>();
1018 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
1019 unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1020
1021 // Abbrev for TYPE_CODE_FUNCTION.
1022 Abbv = std::make_shared<BitCodeAbbrev>();
1024 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
1026 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1027 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1028
1029 // Abbrev for TYPE_CODE_STRUCT_ANON.
1030 Abbv = std::make_shared<BitCodeAbbrev>();
1032 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1034 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1035 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1036
1037 // Abbrev for TYPE_CODE_STRUCT_NAME.
1038 Abbv = std::make_shared<BitCodeAbbrev>();
1042 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1043
1044 // Abbrev for TYPE_CODE_STRUCT_NAMED.
1045 Abbv = std::make_shared<BitCodeAbbrev>();
1047 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1049 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1050 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1051
1052 // Abbrev for TYPE_CODE_ARRAY.
1053 Abbv = std::make_shared<BitCodeAbbrev>();
1055 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
1056 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1057 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1058
1059 // Emit an entry count so the reader can reserve space.
1060 TypeVals.push_back(TypeList.size());
1061 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
1062 TypeVals.clear();
1063
1064 // Loop over all of the types, emitting each in turn.
1065 for (Type *T : TypeList) {
1066 int AbbrevToUse = 0;
1067 unsigned Code = 0;
1068
1069 switch (T->getTypeID()) {
1083 case Type::IntegerTyID:
1084 // INTEGER: [width]
1086 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
1087 break;
1088 case Type::PointerTyID: {
1089 PointerType *PTy = cast<PointerType>(T);
1090 unsigned AddressSpace = PTy->getAddressSpace();
1091 // OPAQUE_POINTER: [address space]
1093 TypeVals.push_back(AddressSpace);
1094 if (AddressSpace == 0)
1095 AbbrevToUse = OpaquePtrAbbrev;
1096 break;
1097 }
1098 case Type::FunctionTyID: {
1099 FunctionType *FT = cast<FunctionType>(T);
1100 // FUNCTION: [isvararg, retty, paramty x N]
1102 TypeVals.push_back(FT->isVarArg());
1103 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
1104 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1105 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
1106 AbbrevToUse = FunctionAbbrev;
1107 break;
1108 }
1109 case Type::StructTyID: {
1110 StructType *ST = cast<StructType>(T);
1111 // STRUCT: [ispacked, eltty x N]
1112 TypeVals.push_back(ST->isPacked());
1113 // Output all of the element types.
1114 for (Type *ET : ST->elements())
1115 TypeVals.push_back(VE.getTypeID(ET));
1116
1117 if (ST->isLiteral()) {
1119 AbbrevToUse = StructAnonAbbrev;
1120 } else {
1121 if (ST->isOpaque()) {
1123 } else {
1125 AbbrevToUse = StructNamedAbbrev;
1126 }
1127
1128 // Emit the name if it is present.
1129 if (!ST->getName().empty())
1131 StructNameAbbrev);
1132 }
1133 break;
1134 }
1135 case Type::ArrayTyID: {
1136 ArrayType *AT = cast<ArrayType>(T);
1137 // ARRAY: [numelts, eltty]
1139 TypeVals.push_back(AT->getNumElements());
1140 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1141 AbbrevToUse = ArrayAbbrev;
1142 break;
1143 }
1146 VectorType *VT = cast<VectorType>(T);
1147 // VECTOR [numelts, eltty] or
1148 // [numelts, eltty, scalable]
1150 TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1151 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1152 if (isa<ScalableVectorType>(VT))
1153 TypeVals.push_back(true);
1154 break;
1155 }
1156 case Type::TargetExtTyID: {
1157 TargetExtType *TET = cast<TargetExtType>(T);
1160 StructNameAbbrev);
1161 TypeVals.push_back(TET->getNumTypeParameters());
1162 for (Type *InnerTy : TET->type_params())
1163 TypeVals.push_back(VE.getTypeID(InnerTy));
1164 for (unsigned IntParam : TET->int_params())
1165 TypeVals.push_back(IntParam);
1166 break;
1167 }
1169 llvm_unreachable("Typed pointers cannot be added to IR modules");
1170 }
1171
1172 // Emit the finished record.
1173 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1174 TypeVals.clear();
1175 }
1176
1177 Stream.ExitBlock();
1178}
1179
1180static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
1181 switch (Linkage) {
1183 return 0;
1185 return 16;
1187 return 2;
1189 return 3;
1191 return 18;
1193 return 7;
1195 return 8;
1197 return 9;
1199 return 17;
1201 return 19;
1203 return 12;
1204 }
1205 llvm_unreachable("Invalid linkage");
1206}
1207
1208static unsigned getEncodedLinkage(const GlobalValue &GV) {
1209 return getEncodedLinkage(GV.getLinkage());
1210}
1211
1213 uint64_t RawFlags = 0;
1214 RawFlags |= Flags.ReadNone;
1215 RawFlags |= (Flags.ReadOnly << 1);
1216 RawFlags |= (Flags.NoRecurse << 2);
1217 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1218 RawFlags |= (Flags.NoInline << 4);
1219 RawFlags |= (Flags.AlwaysInline << 5);
1220 RawFlags |= (Flags.NoUnwind << 6);
1221 RawFlags |= (Flags.MayThrow << 7);
1222 RawFlags |= (Flags.HasUnknownCall << 8);
1223 RawFlags |= (Flags.MustBeUnreachable << 9);
1224 return RawFlags;
1225}
1226
1227// Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1228// in BitcodeReader.cpp.
1230 uint64_t RawFlags = 0;
1231
1232 RawFlags |= Flags.NotEligibleToImport; // bool
1233 RawFlags |= (Flags.Live << 1);
1234 RawFlags |= (Flags.DSOLocal << 2);
1235 RawFlags |= (Flags.CanAutoHide << 3);
1236
1237 // Linkage don't need to be remapped at that time for the summary. Any future
1238 // change to the getEncodedLinkage() function will need to be taken into
1239 // account here as well.
1240 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1241
1242 RawFlags |= (Flags.Visibility << 8); // 2 bits
1243
1244 RawFlags |= (Flags.ImportType << 10); // 1 bit
1245
1246 return RawFlags;
1247}
1248
1250 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1251 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1252 return RawFlags;
1253}
1254
1256 uint64_t RawFlags = 0;
1257
1258 RawFlags |= CI.Hotness; // 3 bits
1259 RawFlags |= (CI.HasTailCall << 3); // 1 bit
1260
1261 return RawFlags;
1262}
1263
1265 uint64_t RawFlags = 0;
1266
1267 RawFlags |= CI.RelBlockFreq; // CalleeInfo::RelBlockFreqBits bits
1268 RawFlags |= (CI.HasTailCall << CalleeInfo::RelBlockFreqBits); // 1 bit
1269
1270 return RawFlags;
1271}
1272
1273static unsigned getEncodedVisibility(const GlobalValue &GV) {
1274 switch (GV.getVisibility()) {
1275 case GlobalValue::DefaultVisibility: return 0;
1276 case GlobalValue::HiddenVisibility: return 1;
1277 case GlobalValue::ProtectedVisibility: return 2;
1278 }
1279 llvm_unreachable("Invalid visibility");
1280}
1281
1282static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1283 switch (GV.getDLLStorageClass()) {
1284 case GlobalValue::DefaultStorageClass: return 0;
1287 }
1288 llvm_unreachable("Invalid DLL storage class");
1289}
1290
1291static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1292 switch (GV.getThreadLocalMode()) {
1293 case GlobalVariable::NotThreadLocal: return 0;
1294 case GlobalVariable::GeneralDynamicTLSModel: return 1;
1295 case GlobalVariable::LocalDynamicTLSModel: return 2;
1296 case GlobalVariable::InitialExecTLSModel: return 3;
1297 case GlobalVariable::LocalExecTLSModel: return 4;
1298 }
1299 llvm_unreachable("Invalid TLS model");
1300}
1301
1302static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1303 switch (C.getSelectionKind()) {
1304 case Comdat::Any:
1306 case Comdat::ExactMatch:
1308 case Comdat::Largest:
1312 case Comdat::SameSize:
1314 }
1315 llvm_unreachable("Invalid selection kind");
1316}
1317
1318static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1319 switch (GV.getUnnamedAddr()) {
1320 case GlobalValue::UnnamedAddr::None: return 0;
1321 case GlobalValue::UnnamedAddr::Local: return 2;
1322 case GlobalValue::UnnamedAddr::Global: return 1;
1323 }
1324 llvm_unreachable("Invalid unnamed_addr");
1325}
1326
1327size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1328 if (GenerateHash)
1329 Hasher.update(Str);
1330 return StrtabBuilder.add(Str);
1331}
1332
1333void ModuleBitcodeWriter::writeComdats() {
1335 for (const Comdat *C : VE.getComdats()) {
1336 // COMDAT: [strtab offset, strtab size, selection_kind]
1337 Vals.push_back(addToStrtab(C->getName()));
1338 Vals.push_back(C->getName().size());
1340 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1341 Vals.clear();
1342 }
1343}
1344
1345/// Write a record that will eventually hold the word offset of the
1346/// module-level VST. For now the offset is 0, which will be backpatched
1347/// after the real VST is written. Saves the bit offset to backpatch.
1348void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1349 // Write a placeholder value in for the offset of the real VST,
1350 // which is written after the function blocks so that it can include
1351 // the offset of each function. The placeholder offset will be
1352 // updated when the real VST is written.
1353 auto Abbv = std::make_shared<BitCodeAbbrev>();
1355 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1356 // hold the real VST offset. Must use fixed instead of VBR as we don't
1357 // know how many VBR chunks to reserve ahead of time.
1359 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1360
1361 // Emit the placeholder
1363 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1364
1365 // Compute and save the bit offset to the placeholder, which will be
1366 // patched when the real VST is written. We can simply subtract the 32-bit
1367 // fixed size from the current bit number to get the location to backpatch.
1368 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1369}
1370
1372
1373/// Determine the encoding to use for the given string name and length.
1375 bool isChar6 = true;
1376 for (char C : Str) {
1377 if (isChar6)
1378 isChar6 = BitCodeAbbrevOp::isChar6(C);
1379 if ((unsigned char)C & 128)
1380 // don't bother scanning the rest.
1381 return SE_Fixed8;
1382 }
1383 if (isChar6)
1384 return SE_Char6;
1385 return SE_Fixed7;
1386}
1387
1388static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
1389 "Sanitizer Metadata is too large for naive serialization.");
1390static unsigned
1392 return Meta.NoAddress | (Meta.NoHWAddress << 1) |
1393 (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
1394}
1395
1396/// Emit top-level description of module, including target triple, inline asm,
1397/// descriptors for global variables, and function prototype info.
1398/// Returns the bit offset to backpatch with the location of the real VST.
1399void ModuleBitcodeWriter::writeModuleInfo() {
1400 // Emit various pieces of data attached to a module.
1401 if (!M.getTargetTriple().empty())
1402 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1403 0 /*TODO*/);
1404 const std::string &DL = M.getDataLayoutStr();
1405 if (!DL.empty())
1407 if (!M.getModuleInlineAsm().empty())
1408 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1409 0 /*TODO*/);
1410
1411 // Emit information about sections and GC, computing how many there are. Also
1412 // compute the maximum alignment value.
1413 std::map<std::string, unsigned> SectionMap;
1414 std::map<std::string, unsigned> GCMap;
1415 MaybeAlign MaxAlignment;
1416 unsigned MaxGlobalType = 0;
1417 const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1418 if (A)
1419 MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1420 };
1421 for (const GlobalVariable &GV : M.globals()) {
1422 UpdateMaxAlignment(GV.getAlign());
1423 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1424 if (GV.hasSection()) {
1425 // Give section names unique ID's.
1426 unsigned &Entry = SectionMap[std::string(GV.getSection())];
1427 if (!Entry) {
1428 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1429 0 /*TODO*/);
1430 Entry = SectionMap.size();
1431 }
1432 }
1433 }
1434 for (const Function &F : M) {
1435 UpdateMaxAlignment(F.getAlign());
1436 if (F.hasSection()) {
1437 // Give section names unique ID's.
1438 unsigned &Entry = SectionMap[std::string(F.getSection())];
1439 if (!Entry) {
1441 0 /*TODO*/);
1442 Entry = SectionMap.size();
1443 }
1444 }
1445 if (F.hasGC()) {
1446 // Same for GC names.
1447 unsigned &Entry = GCMap[F.getGC()];
1448 if (!Entry) {
1450 0 /*TODO*/);
1451 Entry = GCMap.size();
1452 }
1453 }
1454 }
1455
1456 // Emit abbrev for globals, now that we know # sections and max alignment.
1457 unsigned SimpleGVarAbbrev = 0;
1458 if (!M.global_empty()) {
1459 // Add an abbrev for common globals with no visibility or thread localness.
1460 auto Abbv = std::make_shared<BitCodeAbbrev>();
1465 Log2_32_Ceil(MaxGlobalType+1)));
1466 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1467 //| explicitType << 1
1468 //| constant
1469 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1470 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1471 if (!MaxAlignment) // Alignment.
1472 Abbv->Add(BitCodeAbbrevOp(0));
1473 else {
1474 unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
1476 Log2_32_Ceil(MaxEncAlignment+1)));
1477 }
1478 if (SectionMap.empty()) // Section.
1479 Abbv->Add(BitCodeAbbrevOp(0));
1480 else
1482 Log2_32_Ceil(SectionMap.size()+1)));
1483 // Don't bother emitting vis + thread local.
1484 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1485 }
1486
1488 // Emit the module's source file name.
1489 {
1490 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1492 if (Bits == SE_Char6)
1493 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1494 else if (Bits == SE_Fixed7)
1495 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1496
1497 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1498 auto Abbv = std::make_shared<BitCodeAbbrev>();
1501 Abbv->Add(AbbrevOpToUse);
1502 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1503
1504 for (const auto P : M.getSourceFileName())
1505 Vals.push_back((unsigned char)P);
1506
1507 // Emit the finished record.
1508 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1509 Vals.clear();
1510 }
1511
1512 // Emit the global variable information.
1513 for (const GlobalVariable &GV : M.globals()) {
1514 unsigned AbbrevToUse = 0;
1515
1516 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1517 // linkage, alignment, section, visibility, threadlocal,
1518 // unnamed_addr, externally_initialized, dllstorageclass,
1519 // comdat, attributes, DSO_Local, GlobalSanitizer, code_model]
1520 Vals.push_back(addToStrtab(GV.getName()));
1521 Vals.push_back(GV.getName().size());
1522 Vals.push_back(VE.getTypeID(GV.getValueType()));
1523 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1524 Vals.push_back(GV.isDeclaration() ? 0 :
1525 (VE.getValueID(GV.getInitializer()) + 1));
1526 Vals.push_back(getEncodedLinkage(GV));
1527 Vals.push_back(getEncodedAlign(GV.getAlign()));
1528 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1529 : 0);
1530 if (GV.isThreadLocal() ||
1531 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1532 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1533 GV.isExternallyInitialized() ||
1534 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1535 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1536 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1540 Vals.push_back(GV.isExternallyInitialized());
1542 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1543
1544 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1545 Vals.push_back(VE.getAttributeListID(AL));
1546
1547 Vals.push_back(GV.isDSOLocal());
1548 Vals.push_back(addToStrtab(GV.getPartition()));
1549 Vals.push_back(GV.getPartition().size());
1550
1551 Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
1552 GV.getSanitizerMetadata())
1553 : 0));
1554 Vals.push_back(GV.getCodeModelRaw());
1555 } else {
1556 AbbrevToUse = SimpleGVarAbbrev;
1557 }
1558
1559 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1560 Vals.clear();
1561 }
1562
1563 // Emit the function proto information.
1564 for (const Function &F : M) {
1565 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1566 // linkage, paramattrs, alignment, section, visibility, gc,
1567 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1568 // prefixdata, personalityfn, DSO_Local, addrspace]
1569 Vals.push_back(addToStrtab(F.getName()));
1570 Vals.push_back(F.getName().size());
1571 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1572 Vals.push_back(F.getCallingConv());
1573 Vals.push_back(F.isDeclaration());
1575 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1576 Vals.push_back(getEncodedAlign(F.getAlign()));
1577 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1578 : 0);
1580 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1582 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1583 : 0);
1585 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1586 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1587 : 0);
1588 Vals.push_back(
1589 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1590
1591 Vals.push_back(F.isDSOLocal());
1592 Vals.push_back(F.getAddressSpace());
1593 Vals.push_back(addToStrtab(F.getPartition()));
1594 Vals.push_back(F.getPartition().size());
1595
1596 unsigned AbbrevToUse = 0;
1597 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1598 Vals.clear();
1599 }
1600
1601 // Emit the alias information.
1602 for (const GlobalAlias &A : M.aliases()) {
1603 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1604 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1605 // DSO_Local]
1606 Vals.push_back(addToStrtab(A.getName()));
1607 Vals.push_back(A.getName().size());
1608 Vals.push_back(VE.getTypeID(A.getValueType()));
1609 Vals.push_back(A.getType()->getAddressSpace());
1610 Vals.push_back(VE.getValueID(A.getAliasee()));
1616 Vals.push_back(A.isDSOLocal());
1617 Vals.push_back(addToStrtab(A.getPartition()));
1618 Vals.push_back(A.getPartition().size());
1619
1620 unsigned AbbrevToUse = 0;
1621 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1622 Vals.clear();
1623 }
1624
1625 // Emit the ifunc information.
1626 for (const GlobalIFunc &I : M.ifuncs()) {
1627 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1628 // val#, linkage, visibility, DSO_Local]
1629 Vals.push_back(addToStrtab(I.getName()));
1630 Vals.push_back(I.getName().size());
1631 Vals.push_back(VE.getTypeID(I.getValueType()));
1632 Vals.push_back(I.getType()->getAddressSpace());
1633 Vals.push_back(VE.getValueID(I.getResolver()));
1636 Vals.push_back(I.isDSOLocal());
1637 Vals.push_back(addToStrtab(I.getPartition()));
1638 Vals.push_back(I.getPartition().size());
1639 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1640 Vals.clear();
1641 }
1642
1643 writeValueSymbolTableForwardDecl();
1644}
1645
1647 uint64_t Flags = 0;
1648
1649 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1650 if (OBO->hasNoSignedWrap())
1651 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1652 if (OBO->hasNoUnsignedWrap())
1653 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1654 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1655 if (PEO->isExact())
1656 Flags |= 1 << bitc::PEO_EXACT;
1657 } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {
1658 if (PDI->isDisjoint())
1659 Flags |= 1 << bitc::PDI_DISJOINT;
1660 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1661 if (FPMO->hasAllowReassoc())
1662 Flags |= bitc::AllowReassoc;
1663 if (FPMO->hasNoNaNs())
1664 Flags |= bitc::NoNaNs;
1665 if (FPMO->hasNoInfs())
1666 Flags |= bitc::NoInfs;
1667 if (FPMO->hasNoSignedZeros())
1668 Flags |= bitc::NoSignedZeros;
1669 if (FPMO->hasAllowReciprocal())
1670 Flags |= bitc::AllowReciprocal;
1671 if (FPMO->hasAllowContract())
1672 Flags |= bitc::AllowContract;
1673 if (FPMO->hasApproxFunc())
1674 Flags |= bitc::ApproxFunc;
1675 } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1676 if (NNI->hasNonNeg())
1677 Flags |= 1 << bitc::PNNI_NON_NEG;
1678 } else if (const auto *TI = dyn_cast<TruncInst>(V)) {
1679 if (TI->hasNoSignedWrap())
1680 Flags |= 1 << bitc::TIO_NO_SIGNED_WRAP;
1681 if (TI->hasNoUnsignedWrap())
1682 Flags |= 1 << bitc::TIO_NO_UNSIGNED_WRAP;
1683 } else if (const auto *GEP = dyn_cast<GEPOperator>(V)) {
1684 if (GEP->isInBounds())
1685 Flags |= 1 << bitc::GEP_INBOUNDS;
1686 if (GEP->hasNoUnsignedSignedWrap())
1687 Flags |= 1 << bitc::GEP_NUSW;
1688 if (GEP->hasNoUnsignedWrap())
1689 Flags |= 1 << bitc::GEP_NUW;
1690 }
1691
1692 return Flags;
1693}
1694
1695void ModuleBitcodeWriter::writeValueAsMetadata(
1697 // Mimic an MDNode with a value as one operand.
1698 Value *V = MD->getValue();
1699 Record.push_back(VE.getTypeID(V->getType()));
1700 Record.push_back(VE.getValueID(V));
1702 Record.clear();
1703}
1704
1705void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1707 unsigned Abbrev) {
1708 for (const MDOperand &MDO : N->operands()) {
1709 Metadata *MD = MDO;
1710 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1711 "Unexpected function-local metadata");
1712 Record.push_back(VE.getMetadataOrNullID(MD));
1713 }
1714 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1716 Record, Abbrev);
1717 Record.clear();
1718}
1719
1720unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1721 // Assume the column is usually under 128, and always output the inlined-at
1722 // location (it's never more expensive than building an array size 1).
1723 auto Abbv = std::make_shared<BitCodeAbbrev>();
1731 return Stream.EmitAbbrev(std::move(Abbv));
1732}
1733
1734void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1736 unsigned &Abbrev) {
1737 if (!Abbrev)
1738 Abbrev = createDILocationAbbrev();
1739
1740 Record.push_back(N->isDistinct());
1741 Record.push_back(N->getLine());
1742 Record.push_back(N->getColumn());
1743 Record.push_back(VE.getMetadataID(N->getScope()));
1744 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1745 Record.push_back(N->isImplicitCode());
1746
1747 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1748 Record.clear();
1749}
1750
1751unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1752 // Assume the column is usually under 128, and always output the inlined-at
1753 // location (it's never more expensive than building an array size 1).
1754 auto Abbv = std::make_shared<BitCodeAbbrev>();
1762 return Stream.EmitAbbrev(std::move(Abbv));
1763}
1764
1765void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1767 unsigned &Abbrev) {
1768 if (!Abbrev)
1769 Abbrev = createGenericDINodeAbbrev();
1770
1771 Record.push_back(N->isDistinct());
1772 Record.push_back(N->getTag());
1773 Record.push_back(0); // Per-tag version field; unused for now.
1774
1775 for (auto &I : N->operands())
1776 Record.push_back(VE.getMetadataOrNullID(I));
1777
1779 Record.clear();
1780}
1781
1782void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1784 unsigned Abbrev) {
1785 const uint64_t Version = 2 << 1;
1786 Record.push_back((uint64_t)N->isDistinct() | Version);
1787 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1788 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1789 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1790 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1791
1792 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1793 Record.clear();
1794}
1795
1796void ModuleBitcodeWriter::writeDIGenericSubrange(
1798 unsigned Abbrev) {
1799 Record.push_back((uint64_t)N->isDistinct());
1800 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1801 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1802 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1803 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1804
1806 Record.clear();
1807}
1808
1809void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1811 unsigned Abbrev) {
1812 const uint64_t IsBigInt = 1 << 2;
1813 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
1814 Record.push_back(N->getValue().getBitWidth());
1815 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1816 emitWideAPInt(Record, N->getValue());
1817
1819 Record.clear();
1820}
1821
1822void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1824 unsigned Abbrev) {
1825 Record.push_back(N->isDistinct());
1826 Record.push_back(N->getTag());
1827 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1828 Record.push_back(N->getSizeInBits());
1829 Record.push_back(N->getAlignInBits());
1830 Record.push_back(N->getEncoding());
1831 Record.push_back(N->getFlags());
1832
1834 Record.clear();
1835}
1836
1837void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
1839 unsigned Abbrev) {
1840 Record.push_back(N->isDistinct());
1841 Record.push_back(N->getTag());
1842 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1843 Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1844 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
1845 Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
1846 Record.push_back(N->getSizeInBits());
1847 Record.push_back(N->getAlignInBits());
1848 Record.push_back(N->getEncoding());
1849
1851 Record.clear();
1852}
1853
1854void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1856 unsigned Abbrev) {
1857 Record.push_back(N->isDistinct());
1858 Record.push_back(N->getTag());
1859 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1860 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1861 Record.push_back(N->getLine());
1862 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1863 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1864 Record.push_back(N->getSizeInBits());
1865 Record.push_back(N->getAlignInBits());
1866 Record.push_back(N->getOffsetInBits());
1867 Record.push_back(N->getFlags());
1868 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1869
1870 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1871 // that there is no DWARF address space associated with DIDerivedType.
1872 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1873 Record.push_back(*DWARFAddressSpace + 1);
1874 else
1875 Record.push_back(0);
1876
1877 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1878
1879 if (auto PtrAuthData = N->getPtrAuthData())
1880 Record.push_back(PtrAuthData->RawData);
1881 else
1882 Record.push_back(0);
1883
1885 Record.clear();
1886}
1887
1888void ModuleBitcodeWriter::writeDICompositeType(
1890 unsigned Abbrev) {
1891 const unsigned IsNotUsedInOldTypeRef = 0x2;
1892 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1893 Record.push_back(N->getTag());
1894 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1895 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1896 Record.push_back(N->getLine());
1897 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1898 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1899 Record.push_back(N->getSizeInBits());
1900 Record.push_back(N->getAlignInBits());
1901 Record.push_back(N->getOffsetInBits());
1902 Record.push_back(N->getFlags());
1903 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1904 Record.push_back(N->getRuntimeLang());
1905 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1906 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1907 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1908 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
1909 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1910 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1911 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1912 Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
1913 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1914
1916 Record.clear();
1917}
1918
1919void ModuleBitcodeWriter::writeDISubroutineType(
1921 unsigned Abbrev) {
1922 const unsigned HasNoOldTypeRefs = 0x2;
1923 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1924 Record.push_back(N->getFlags());
1925 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1926 Record.push_back(N->getCC());
1927
1929 Record.clear();
1930}
1931
1932void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1934 unsigned Abbrev) {
1935 Record.push_back(N->isDistinct());
1936 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1937 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1938 if (N->getRawChecksum()) {
1939 Record.push_back(N->getRawChecksum()->Kind);
1940 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1941 } else {
1942 // Maintain backwards compatibility with the old internal representation of
1943 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1944 Record.push_back(0);
1945 Record.push_back(VE.getMetadataOrNullID(nullptr));
1946 }
1947 auto Source = N->getRawSource();
1948 if (Source)
1949 Record.push_back(VE.getMetadataOrNullID(Source));
1950
1951 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1952 Record.clear();
1953}
1954
1955void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1957 unsigned Abbrev) {
1958 assert(N->isDistinct() && "Expected distinct compile units");
1959 Record.push_back(/* IsDistinct */ true);
1960 Record.push_back(N->getSourceLanguage());
1961 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1962 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1963 Record.push_back(N->isOptimized());
1964 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1965 Record.push_back(N->getRuntimeVersion());
1966 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1967 Record.push_back(N->getEmissionKind());
1968 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1969 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1970 Record.push_back(/* subprograms */ 0);
1971 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1972 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1973 Record.push_back(N->getDWOId());
1974 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1975 Record.push_back(N->getSplitDebugInlining());
1976 Record.push_back(N->getDebugInfoForProfiling());
1977 Record.push_back((unsigned)N->getNameTableKind());
1978 Record.push_back(N->getRangesBaseAddress());
1979 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
1980 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
1981
1983 Record.clear();
1984}
1985
1986void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1988 unsigned Abbrev) {
1989 const uint64_t HasUnitFlag = 1 << 1;
1990 const uint64_t HasSPFlagsFlag = 1 << 2;
1991 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
1992 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1993 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1994 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1995 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1996 Record.push_back(N->getLine());
1997 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1998 Record.push_back(N->getScopeLine());
1999 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
2000 Record.push_back(N->getSPFlags());
2001 Record.push_back(N->getVirtualIndex());
2002 Record.push_back(N->getFlags());
2003 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
2004 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2005 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
2006 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
2007 Record.push_back(N->getThisAdjustment());
2008 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
2009 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2010 Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
2011
2013 Record.clear();
2014}
2015
2016void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
2018 unsigned Abbrev) {
2019 Record.push_back(N->isDistinct());
2020 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2021 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2022 Record.push_back(N->getLine());
2023 Record.push_back(N->getColumn());
2024
2026 Record.clear();
2027}
2028
2029void ModuleBitcodeWriter::writeDILexicalBlockFile(
2031 unsigned Abbrev) {
2032 Record.push_back(N->isDistinct());
2033 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2034 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2035 Record.push_back(N->getDiscriminator());
2036
2038 Record.clear();
2039}
2040
2041void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
2043 unsigned Abbrev) {
2044 Record.push_back(N->isDistinct());
2045 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2046 Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
2047 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2048 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2049 Record.push_back(N->getLineNo());
2050
2052 Record.clear();
2053}
2054
2055void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
2057 unsigned Abbrev) {
2058 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
2059 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2060 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2061
2063 Record.clear();
2064}
2065
2066void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
2068 unsigned Abbrev) {
2069 Record.push_back(N->isDistinct());
2070 Record.push_back(N->getMacinfoType());
2071 Record.push_back(N->getLine());
2072 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2073 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
2074
2075 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
2076 Record.clear();
2077}
2078
2079void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
2081 unsigned Abbrev) {
2082 Record.push_back(N->isDistinct());
2083 Record.push_back(N->getMacinfoType());
2084 Record.push_back(N->getLine());
2085 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2086 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2087
2089 Record.clear();
2090}
2091
2092void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
2094 Record.reserve(N->getArgs().size());
2095 for (ValueAsMetadata *MD : N->getArgs())
2096 Record.push_back(VE.getMetadataID(MD));
2097
2099 Record.clear();
2100}
2101
2102void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
2104 unsigned Abbrev) {
2105 Record.push_back(N->isDistinct());
2106 for (auto &I : N->operands())
2107 Record.push_back(VE.getMetadataOrNullID(I));
2108 Record.push_back(N->getLineNo());
2109 Record.push_back(N->getIsDecl());
2110
2111 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
2112 Record.clear();
2113}
2114
2115void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
2117 unsigned Abbrev) {
2118 // There are no arguments for this metadata type.
2119 Record.push_back(N->isDistinct());
2121 Record.clear();
2122}
2123
2124void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2126 unsigned Abbrev) {
2127 Record.push_back(N->isDistinct());
2128 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2129 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2130 Record.push_back(N->isDefault());
2131
2133 Record.clear();
2134}
2135
2136void ModuleBitcodeWriter::writeDITemplateValueParameter(
2138 unsigned Abbrev) {
2139 Record.push_back(N->isDistinct());
2140 Record.push_back(N->getTag());
2141 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2142 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2143 Record.push_back(N->isDefault());
2144 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
2145
2147 Record.clear();
2148}
2149
2150void ModuleBitcodeWriter::writeDIGlobalVariable(
2152 unsigned Abbrev) {
2153 const uint64_t Version = 2 << 1;
2154 Record.push_back((uint64_t)N->isDistinct() | Version);
2155 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2156 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2157 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2158 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2159 Record.push_back(N->getLine());
2160 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2161 Record.push_back(N->isLocalToUnit());
2162 Record.push_back(N->isDefinition());
2163 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
2164 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
2165 Record.push_back(N->getAlignInBits());
2166 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2167
2169 Record.clear();
2170}
2171
2172void ModuleBitcodeWriter::writeDILocalVariable(
2174 unsigned Abbrev) {
2175 // In order to support all possible bitcode formats in BitcodeReader we need
2176 // to distinguish the following cases:
2177 // 1) Record has no artificial tag (Record[1]),
2178 // has no obsolete inlinedAt field (Record[9]).
2179 // In this case Record size will be 8, HasAlignment flag is false.
2180 // 2) Record has artificial tag (Record[1]),
2181 // has no obsolete inlignedAt field (Record[9]).
2182 // In this case Record size will be 9, HasAlignment flag is false.
2183 // 3) Record has both artificial tag (Record[1]) and
2184 // obsolete inlignedAt field (Record[9]).
2185 // In this case Record size will be 10, HasAlignment flag is false.
2186 // 4) Record has neither artificial tag, nor inlignedAt field, but
2187 // HasAlignment flag is true and Record[8] contains alignment value.
2188 const uint64_t HasAlignmentFlag = 1 << 1;
2189 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2190 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2191 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2192 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2193 Record.push_back(N->getLine());
2194 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2195 Record.push_back(N->getArg());
2196 Record.push_back(N->getFlags());
2197 Record.push_back(N->getAlignInBits());
2198 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2199
2201 Record.clear();
2202}
2203
2204void ModuleBitcodeWriter::writeDILabel(
2206 unsigned Abbrev) {
2207 Record.push_back((uint64_t)N->isDistinct());
2208 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2209 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2210 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2211 Record.push_back(N->getLine());
2212
2213 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2214 Record.clear();
2215}
2216
2217void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
2219 unsigned Abbrev) {
2220 Record.reserve(N->getElements().size() + 1);
2221 const uint64_t Version = 3 << 1;
2222 Record.push_back((uint64_t)N->isDistinct() | Version);
2223 Record.append(N->elements_begin(), N->elements_end());
2224
2226 Record.clear();
2227}
2228
2229void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2231 unsigned Abbrev) {
2232 Record.push_back(N->isDistinct());
2233 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2234 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2235
2237 Record.clear();
2238}
2239
2240void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
2242 unsigned Abbrev) {
2243 Record.push_back(N->isDistinct());
2244 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2245 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2246 Record.push_back(N->getLine());
2247 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2248 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2249 Record.push_back(N->getAttributes());
2250 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2251
2253 Record.clear();
2254}
2255
2256void ModuleBitcodeWriter::writeDIImportedEntity(
2258 unsigned Abbrev) {
2259 Record.push_back(N->isDistinct());
2260 Record.push_back(N->getTag());
2261 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2262 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2263 Record.push_back(N->getLine());
2264 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2265 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2266 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2267
2269 Record.clear();
2270}
2271
2272unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2273 auto Abbv = std::make_shared<BitCodeAbbrev>();
2277 return Stream.EmitAbbrev(std::move(Abbv));
2278}
2279
2280void ModuleBitcodeWriter::writeNamedMetadata(
2282 if (M.named_metadata_empty())
2283 return;
2284
2285 unsigned Abbrev = createNamedMetadataAbbrev();
2286 for (const NamedMDNode &NMD : M.named_metadata()) {
2287 // Write name.
2288 StringRef Str = NMD.getName();
2289 Record.append(Str.bytes_begin(), Str.bytes_end());
2290 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2291 Record.clear();
2292
2293 // Write named metadata operands.
2294 for (const MDNode *N : NMD.operands())
2295 Record.push_back(VE.getMetadataID(N));
2297 Record.clear();
2298 }
2299}
2300
2301unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2302 auto Abbv = std::make_shared<BitCodeAbbrev>();
2304 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2305 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2307 return Stream.EmitAbbrev(std::move(Abbv));
2308}
2309
2310/// Write out a record for MDString.
2311///
2312/// All the metadata strings in a metadata block are emitted in a single
2313/// record. The sizes and strings themselves are shoved into a blob.
2314void ModuleBitcodeWriter::writeMetadataStrings(
2316 if (Strings.empty())
2317 return;
2318
2319 // Start the record with the number of strings.
2320 Record.push_back(bitc::METADATA_STRINGS);
2321 Record.push_back(Strings.size());
2322
2323 // Emit the sizes of the strings in the blob.
2324 SmallString<256> Blob;
2325 {
2326 BitstreamWriter W(Blob);
2327 for (const Metadata *MD : Strings)
2328 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2329 W.FlushToWord();
2330 }
2331
2332 // Add the offset to the strings to the record.
2333 Record.push_back(Blob.size());
2334
2335 // Add the strings to the blob.
2336 for (const Metadata *MD : Strings)
2337 Blob.append(cast<MDString>(MD)->getString());
2338
2339 // Emit the final record.
2340 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2341 Record.clear();
2342}
2343
2344// Generates an enum to use as an index in the Abbrev array of Metadata record.
2345enum MetadataAbbrev : unsigned {
2346#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2347#include "llvm/IR/Metadata.def"
2350
2351void ModuleBitcodeWriter::writeMetadataRecords(
2353 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2354 if (MDs.empty())
2355 return;
2356
2357 // Initialize MDNode abbreviations.
2358#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2359#include "llvm/IR/Metadata.def"
2360
2361 for (const Metadata *MD : MDs) {
2362 if (IndexPos)
2363 IndexPos->push_back(Stream.GetCurrentBitNo());
2364 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2365 assert(N->isResolved() && "Expected forward references to be resolved");
2366
2367 switch (N->getMetadataID()) {
2368 default:
2369 llvm_unreachable("Invalid MDNode subclass");
2370#define HANDLE_MDNODE_LEAF(CLASS) \
2371 case Metadata::CLASS##Kind: \
2372 if (MDAbbrevs) \
2373 write##CLASS(cast<CLASS>(N), Record, \
2374 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2375 else \
2376 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2377 continue;
2378#include "llvm/IR/Metadata.def"
2379 }
2380 }
2381 if (auto *AL = dyn_cast<DIArgList>(MD)) {
2383 continue;
2384 }
2385 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2386 }
2387}
2388
2389void ModuleBitcodeWriter::writeModuleMetadata() {
2390 if (!VE.hasMDs() && M.named_metadata_empty())
2391 return;
2392
2395
2396 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2397 // block and load any metadata.
2398 std::vector<unsigned> MDAbbrevs;
2399
2400 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2401 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2402 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2403 createGenericDINodeAbbrev();
2404
2405 auto Abbv = std::make_shared<BitCodeAbbrev>();
2409 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2410
2411 Abbv = std::make_shared<BitCodeAbbrev>();
2415 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2416
2417 // Emit MDStrings together upfront.
2418 writeMetadataStrings(VE.getMDStrings(), Record);
2419
2420 // We only emit an index for the metadata record if we have more than a given
2421 // (naive) threshold of metadatas, otherwise it is not worth it.
2422 if (VE.getNonMDStrings().size() > IndexThreshold) {
2423 // Write a placeholder value in for the offset of the metadata index,
2424 // which is written after the records, so that it can include
2425 // the offset of each entry. The placeholder offset will be
2426 // updated after all records are emitted.
2427 uint64_t Vals[] = {0, 0};
2428 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2429 }
2430
2431 // Compute and save the bit offset to the current position, which will be
2432 // patched when we emit the index later. We can simply subtract the 64-bit
2433 // fixed size from the current bit number to get the location to backpatch.
2434 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2435
2436 // This index will contain the bitpos for each individual record.
2437 std::vector<uint64_t> IndexPos;
2438 IndexPos.reserve(VE.getNonMDStrings().size());
2439
2440 // Write all the records
2441 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2442
2443 if (VE.getNonMDStrings().size() > IndexThreshold) {
2444 // Now that we have emitted all the records we will emit the index. But
2445 // first
2446 // backpatch the forward reference so that the reader can skip the records
2447 // efficiently.
2448 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2449 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2450
2451 // Delta encode the index.
2452 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2453 for (auto &Elt : IndexPos) {
2454 auto EltDelta = Elt - PreviousValue;
2455 PreviousValue = Elt;
2456 Elt = EltDelta;
2457 }
2458 // Emit the index record.
2459 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2460 IndexPos.clear();
2461 }
2462
2463 // Write the named metadata now.
2464 writeNamedMetadata(Record);
2465
2466 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2468 Record.push_back(VE.getValueID(&GO));
2469 pushGlobalMetadataAttachment(Record, GO);
2471 };
2472 for (const Function &F : M)
2473 if (F.isDeclaration() && F.hasMetadata())
2474 AddDeclAttachedMetadata(F);
2475 // FIXME: Only store metadata for declarations here, and move data for global
2476 // variable definitions to a separate block (PR28134).
2477 for (const GlobalVariable &GV : M.globals())
2478 if (GV.hasMetadata())
2479 AddDeclAttachedMetadata(GV);
2480
2481 Stream.ExitBlock();
2482}
2483
2484void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2485 if (!VE.hasMDs())
2486 return;
2487
2490 writeMetadataStrings(VE.getMDStrings(), Record);
2491 writeMetadataRecords(VE.getNonMDStrings(), Record);
2492 Stream.ExitBlock();
2493}
2494
2495void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2497 // [n x [id, mdnode]]
2499 GO.getAllMetadata(MDs);
2500 for (const auto &I : MDs) {
2501 Record.push_back(I.first);
2502 Record.push_back(VE.getMetadataID(I.second));
2503 }
2504}
2505
2506void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2508
2510
2511 if (F.hasMetadata()) {
2512 pushGlobalMetadataAttachment(Record, F);
2514 Record.clear();
2515 }
2516
2517 // Write metadata attachments
2518 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2520 for (const BasicBlock &BB : F)
2521 for (const Instruction &I : BB) {
2522 MDs.clear();
2523 I.getAllMetadataOtherThanDebugLoc(MDs);
2524
2525 // If no metadata, ignore instruction.
2526 if (MDs.empty()) continue;
2527
2528 Record.push_back(VE.getInstructionID(&I));
2529
2530 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2531 Record.push_back(MDs[i].first);
2532 Record.push_back(VE.getMetadataID(MDs[i].second));
2533 }
2535 Record.clear();
2536 }
2537
2538 Stream.ExitBlock();
2539}
2540
2541void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2543
2544 // Write metadata kinds
2545 // METADATA_KIND - [n x [id, name]]
2547 M.getMDKindNames(Names);
2548
2549 if (Names.empty()) return;
2550
2552
2553 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2554 Record.push_back(MDKindID);
2555 StringRef KName = Names[MDKindID];
2556 Record.append(KName.begin(), KName.end());
2557
2559 Record.clear();
2560 }
2561
2562 Stream.ExitBlock();
2563}
2564
2565void ModuleBitcodeWriter::writeOperandBundleTags() {
2566 // Write metadata kinds
2567 //
2568 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2569 //
2570 // OPERAND_BUNDLE_TAG - [strchr x N]
2571
2573 M.getOperandBundleTags(Tags);
2574
2575 if (Tags.empty())
2576 return;
2577
2579
2581
2582 for (auto Tag : Tags) {
2583 Record.append(Tag.begin(), Tag.end());
2584
2586 Record.clear();
2587 }
2588
2589 Stream.ExitBlock();
2590}
2591
2592void ModuleBitcodeWriter::writeSyncScopeNames() {
2594 M.getContext().getSyncScopeNames(SSNs);
2595 if (SSNs.empty())
2596 return;
2597
2599
2601 for (auto SSN : SSNs) {
2602 Record.append(SSN.begin(), SSN.end());
2604 Record.clear();
2605 }
2606
2607 Stream.ExitBlock();
2608}
2609
2610void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2611 bool isGlobal) {
2612 if (FirstVal == LastVal) return;
2613
2615
2616 unsigned AggregateAbbrev = 0;
2617 unsigned String8Abbrev = 0;
2618 unsigned CString7Abbrev = 0;
2619 unsigned CString6Abbrev = 0;
2620 // If this is a constant pool for the module, emit module-specific abbrevs.
2621 if (isGlobal) {
2622 // Abbrev for CST_CODE_AGGREGATE.
2623 auto Abbv = std::make_shared<BitCodeAbbrev>();
2626 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2627 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2628
2629 // Abbrev for CST_CODE_STRING.
2630 Abbv = std::make_shared<BitCodeAbbrev>();
2634 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2635 // Abbrev for CST_CODE_CSTRING.
2636 Abbv = std::make_shared<BitCodeAbbrev>();
2640 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2641 // Abbrev for CST_CODE_CSTRING.
2642 Abbv = std::make_shared<BitCodeAbbrev>();
2646 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2647 }
2648
2650
2651 const ValueEnumerator::ValueList &Vals = VE.getValues();
2652 Type *LastTy = nullptr;
2653 for (unsigned i = FirstVal; i != LastVal; ++i) {
2654 const Value *V = Vals[i].first;
2655 // If we need to switch types, do so now.
2656 if (V->getType() != LastTy) {
2657 LastTy = V->getType();
2658 Record.push_back(VE.getTypeID(LastTy));
2660 CONSTANTS_SETTYPE_ABBREV);
2661 Record.clear();
2662 }
2663
2664 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2665 Record.push_back(VE.getTypeID(IA->getFunctionType()));
2666 Record.push_back(
2667 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2668 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2669
2670 // Add the asm string.
2671 const std::string &AsmStr = IA->getAsmString();
2672 Record.push_back(AsmStr.size());
2673 Record.append(AsmStr.begin(), AsmStr.end());
2674
2675 // Add the constraint string.
2676 const std::string &ConstraintStr = IA->getConstraintString();
2677 Record.push_back(ConstraintStr.size());
2678 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2680 Record.clear();
2681 continue;
2682 }
2683 const Constant *C = cast<Constant>(V);
2684 unsigned Code = -1U;
2685 unsigned AbbrevToUse = 0;
2686 if (C->isNullValue()) {
2688 } else if (isa<PoisonValue>(C)) {
2690 } else if (isa<UndefValue>(C)) {
2692 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2693 if (IV->getBitWidth() <= 64) {
2694 uint64_t V = IV->getSExtValue();
2697 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2698 } else { // Wide integers, > 64 bits in size.
2699 emitWideAPInt(Record, IV->getValue());
2701 }
2702 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2704 Type *Ty = CFP->getType()->getScalarType();
2705 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2706 Ty->isDoubleTy()) {
2707 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2708 } else if (Ty->isX86_FP80Ty()) {
2709 // api needed to prevent premature destruction
2710 // bits are not in the same order as a normal i80 APInt, compensate.
2711 APInt api = CFP->getValueAPF().bitcastToAPInt();
2712 const uint64_t *p = api.getRawData();
2713 Record.push_back((p[1] << 48) | (p[0] >> 16));
2714 Record.push_back(p[0] & 0xffffLL);
2715 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2716 APInt api = CFP->getValueAPF().bitcastToAPInt();
2717 const uint64_t *p = api.getRawData();
2718 Record.push_back(p[0]);
2719 Record.push_back(p[1]);
2720 } else {
2721 assert(0 && "Unknown FP type!");
2722 }
2723 } else if (isa<ConstantDataSequential>(C) &&
2724 cast<ConstantDataSequential>(C)->isString()) {
2725 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2726 // Emit constant strings specially.
2727 unsigned NumElts = Str->getNumElements();
2728 // If this is a null-terminated string, use the denser CSTRING encoding.
2729 if (Str->isCString()) {
2731 --NumElts; // Don't encode the null, which isn't allowed by char6.
2732 } else {
2734 AbbrevToUse = String8Abbrev;
2735 }
2736 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2737 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2738 for (unsigned i = 0; i != NumElts; ++i) {
2739 unsigned char V = Str->getElementAsInteger(i);
2740 Record.push_back(V);
2741 isCStr7 &= (V & 128) == 0;
2742 if (isCStrChar6)
2743 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2744 }
2745
2746 if (isCStrChar6)
2747 AbbrevToUse = CString6Abbrev;
2748 else if (isCStr7)
2749 AbbrevToUse = CString7Abbrev;
2750 } else if (const ConstantDataSequential *CDS =
2751 dyn_cast<ConstantDataSequential>(C)) {
2753 Type *EltTy = CDS->getElementType();
2754 if (isa<IntegerType>(EltTy)) {
2755 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2756 Record.push_back(CDS->getElementAsInteger(i));
2757 } else {
2758 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2759 Record.push_back(
2760 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2761 }
2762 } else if (isa<ConstantAggregate>(C)) {
2764 for (const Value *Op : C->operands())
2765 Record.push_back(VE.getValueID(Op));
2766 AbbrevToUse = AggregateAbbrev;
2767 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2768 switch (CE->getOpcode()) {
2769 default:
2770 if (Instruction::isCast(CE->getOpcode())) {
2772 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2773 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2774 Record.push_back(VE.getValueID(C->getOperand(0)));
2775 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2776 } else {
2777 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2779 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2780 Record.push_back(VE.getValueID(C->getOperand(0)));
2781 Record.push_back(VE.getValueID(C->getOperand(1)));
2783 if (Flags != 0)
2784 Record.push_back(Flags);
2785 }
2786 break;
2787 case Instruction::FNeg: {
2788 assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2790 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2791 Record.push_back(VE.getValueID(C->getOperand(0)));
2793 if (Flags != 0)
2794 Record.push_back(Flags);
2795 break;
2796 }
2797 case Instruction::GetElementPtr: {
2799 const auto *GO = cast<GEPOperator>(C);
2800 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2801 Record.push_back(getOptimizationFlags(GO));
2802 if (std::optional<ConstantRange> Range = GO->getInRange()) {
2804 emitConstantRange(Record, *Range, /*EmitBitWidth=*/true);
2805 }
2806 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2807 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2808 Record.push_back(VE.getValueID(C->getOperand(i)));
2809 }
2810 break;
2811 }
2812 case Instruction::ExtractElement:
2814 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2815 Record.push_back(VE.getValueID(C->getOperand(0)));
2816 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2817 Record.push_back(VE.getValueID(C->getOperand(1)));
2818 break;
2819 case Instruction::InsertElement:
2821 Record.push_back(VE.getValueID(C->getOperand(0)));
2822 Record.push_back(VE.getValueID(C->getOperand(1)));
2823 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2824 Record.push_back(VE.getValueID(C->getOperand(2)));
2825 break;
2826 case Instruction::ShuffleVector:
2827 // If the return type and argument types are the same, this is a
2828 // standard shufflevector instruction. If the types are different,
2829 // then the shuffle is widening or truncating the input vectors, and
2830 // the argument type must also be encoded.
2831 if (C->getType() == C->getOperand(0)->getType()) {
2833 } else {
2835 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2836 }
2837 Record.push_back(VE.getValueID(C->getOperand(0)));
2838 Record.push_back(VE.getValueID(C->getOperand(1)));
2839 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
2840 break;
2841 }
2842 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2844 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2845 Record.push_back(VE.getValueID(BA->getFunction()));
2846 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2847 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2849 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2850 Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
2851 } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
2853 Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
2854 Record.push_back(VE.getValueID(NC->getGlobalValue()));
2855 } else if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C)) {
2857 Record.push_back(VE.getValueID(CPA->getPointer()));
2858 Record.push_back(VE.getValueID(CPA->getKey()));
2859 Record.push_back(VE.getValueID(CPA->getDiscriminator()));
2860 Record.push_back(VE.getValueID(CPA->getAddrDiscriminator()));
2861 } else {
2862#ifndef NDEBUG
2863 C->dump();
2864#endif
2865 llvm_unreachable("Unknown constant!");
2866 }
2867 Stream.EmitRecord(Code, Record, AbbrevToUse);
2868 Record.clear();
2869 }
2870
2871 Stream.ExitBlock();
2872}
2873
2874void ModuleBitcodeWriter::writeModuleConstants() {
2875 const ValueEnumerator::ValueList &Vals = VE.getValues();
2876
2877 // Find the first constant to emit, which is the first non-globalvalue value.
2878 // We know globalvalues have been emitted by WriteModuleInfo.
2879 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2880 if (!isa<GlobalValue>(Vals[i].first)) {
2881 writeConstants(i, Vals.size(), true);
2882 return;
2883 }
2884 }
2885}
2886
2887/// pushValueAndType - The file has to encode both the value and type id for
2888/// many values, because we need to know what type to create for forward
2889/// references. However, most operands are not forward references, so this type
2890/// field is not needed.
2891///
2892/// This function adds V's value ID to Vals. If the value ID is higher than the
2893/// instruction ID, then it is a forward reference, and it also includes the
2894/// type ID. The value ID that is written is encoded relative to the InstID.
2895bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2897 unsigned ValID = VE.getValueID(V);
2898 // Make encoding relative to the InstID.
2899 Vals.push_back(InstID - ValID);
2900 if (ValID >= InstID) {
2901 Vals.push_back(VE.getTypeID(V->getType()));
2902 return true;
2903 }
2904 return false;
2905}
2906
2907void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
2908 unsigned InstID) {
2910 LLVMContext &C = CS.getContext();
2911
2912 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2913 const auto &Bundle = CS.getOperandBundleAt(i);
2914 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2915
2916 for (auto &Input : Bundle.Inputs)
2917 pushValueAndType(Input, InstID, Record);
2918
2920 Record.clear();
2921 }
2922}
2923
2924/// pushValue - Like pushValueAndType, but where the type of the value is
2925/// omitted (perhaps it was already encoded in an earlier operand).
2926void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2928 unsigned ValID = VE.getValueID(V);
2929 Vals.push_back(InstID - ValID);
2930}
2931
2932void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2934 unsigned ValID = VE.getValueID(V);
2935 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2936 emitSignedInt64(Vals, diff);
2937}
2938
2939/// WriteInstruction - Emit an instruction to the specified stream.
2940void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2941 unsigned InstID,
2943 unsigned Code = 0;
2944 unsigned AbbrevToUse = 0;
2945 VE.setInstructionID(&I);
2946 switch (I.getOpcode()) {
2947 default:
2948 if (Instruction::isCast(I.getOpcode())) {
2950 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2951 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2952 Vals.push_back(VE.getTypeID(I.getType()));
2953 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2955 if (Flags != 0) {
2956 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
2957 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
2958 Vals.push_back(Flags);
2959 }
2960 } else {
2961 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2963 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2964 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2965 pushValue(I.getOperand(1), InstID, Vals);
2966 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2968 if (Flags != 0) {
2969 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2970 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2971 Vals.push_back(Flags);
2972 }
2973 }
2974 break;
2975 case Instruction::FNeg: {
2977 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2978 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2979 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2981 if (Flags != 0) {
2982 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2983 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2984 Vals.push_back(Flags);
2985 }
2986 break;
2987 }
2988 case Instruction::GetElementPtr: {
2990 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2991 auto &GEPInst = cast<GetElementPtrInst>(I);
2993 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2994 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2995 pushValueAndType(I.getOperand(i), InstID, Vals);
2996 break;
2997 }
2998 case Instruction::ExtractValue: {
3000 pushValueAndType(I.getOperand(0), InstID, Vals);
3001 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3002 Vals.append(EVI->idx_begin(), EVI->idx_end());
3003 break;
3004 }
3005 case Instruction::InsertValue: {
3007 pushValueAndType(I.getOperand(0), InstID, Vals);
3008 pushValueAndType(I.getOperand(1), InstID, Vals);
3009 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
3010 Vals.append(IVI->idx_begin(), IVI->idx_end());
3011 break;
3012 }
3013 case Instruction::Select: {
3015 pushValueAndType(I.getOperand(1), InstID, Vals);
3016 pushValue(I.getOperand(2), InstID, Vals);
3017 pushValueAndType(I.getOperand(0), InstID, Vals);
3019 if (Flags != 0)
3020 Vals.push_back(Flags);
3021 break;
3022 }
3023 case Instruction::ExtractElement:
3025 pushValueAndType(I.getOperand(0), InstID, Vals);
3026 pushValueAndType(I.getOperand(1), InstID, Vals);
3027 break;
3028 case Instruction::InsertElement:
3030 pushValueAndType(I.getOperand(0), InstID, Vals);
3031 pushValue(I.getOperand(1), InstID, Vals);
3032 pushValueAndType(I.getOperand(2), InstID, Vals);
3033 break;
3034 case Instruction::ShuffleVector:
3036 pushValueAndType(I.getOperand(0), InstID, Vals);
3037 pushValue(I.getOperand(1), InstID, Vals);
3038 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
3039 Vals);
3040 break;
3041 case Instruction::ICmp:
3042 case Instruction::FCmp: {
3043 // compare returning Int1Ty or vector of Int1Ty
3045 pushValueAndType(I.getOperand(0), InstID, Vals);
3046 pushValue(I.getOperand(1), InstID, Vals);
3047 Vals.push_back(cast<CmpInst>(I).getPredicate());
3049 if (Flags != 0)
3050 Vals.push_back(Flags);
3051 break;
3052 }
3053
3054 case Instruction::Ret:
3055 {
3057 unsigned NumOperands = I.getNumOperands();
3058 if (NumOperands == 0)
3059 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3060 else if (NumOperands == 1) {
3061 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3062 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3063 } else {
3064 for (unsigned i = 0, e = NumOperands; i != e; ++i)
3065 pushValueAndType(I.getOperand(i), InstID, Vals);
3066 }
3067 }
3068 break;
3069 case Instruction::Br:
3070 {
3072 const BranchInst &II = cast<BranchInst>(I);
3073 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3074 if (II.isConditional()) {
3075 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
3076 pushValue(II.getCondition(), InstID, Vals);
3077 }
3078 }
3079 break;
3080 case Instruction::Switch:
3081 {
3083 const SwitchInst &SI = cast<SwitchInst>(I);
3084 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
3085 pushValue(SI.getCondition(), InstID, Vals);
3086 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
3087 for (auto Case : SI.cases()) {
3088 Vals.push_back(VE.getValueID(Case.getCaseValue()));
3089 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
3090 }
3091 }
3092 break;
3093 case Instruction::IndirectBr:
3095 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3096 // Encode the address operand as relative, but not the basic blocks.
3097 pushValue(I.getOperand(0), InstID, Vals);
3098 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
3099 Vals.push_back(VE.getValueID(I.getOperand(i)));
3100 break;
3101
3102 case Instruction::Invoke: {
3103 const InvokeInst *II = cast<InvokeInst>(&I);
3104 const Value *Callee = II->getCalledOperand();
3105 FunctionType *FTy = II->getFunctionType();
3106
3107 if (II->hasOperandBundles())
3108 writeOperandBundles(*II, InstID);
3109
3111
3112 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
3113 Vals.push_back(II->getCallingConv() | 1 << 13);
3114 Vals.push_back(VE.getValueID(II->getNormalDest()));
3115 Vals.push_back(VE.getValueID(II->getUnwindDest()));
3116 Vals.push_back(VE.getTypeID(FTy));
3117 pushValueAndType(Callee, InstID, Vals);
3118
3119 // Emit value #'s for the fixed parameters.
3120 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3121 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3122
3123 // Emit type/value pairs for varargs params.
3124 if (FTy->isVarArg()) {
3125 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
3126 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3127 }
3128 break;
3129 }
3130 case Instruction::Resume:
3132 pushValueAndType(I.getOperand(0), InstID, Vals);
3133 break;
3134 case Instruction::CleanupRet: {
3136 const auto &CRI = cast<CleanupReturnInst>(I);
3137 pushValue(CRI.getCleanupPad(), InstID, Vals);
3138 if (CRI.hasUnwindDest())
3139 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
3140 break;
3141 }
3142 case Instruction::CatchRet: {
3144 const auto &CRI = cast<CatchReturnInst>(I);
3145 pushValue(CRI.getCatchPad(), InstID, Vals);
3146 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
3147 break;
3148 }
3149 case Instruction::CleanupPad:
3150 case Instruction::CatchPad: {
3151 const auto &FuncletPad = cast<FuncletPadInst>(I);
3152 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
3154 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3155
3156 unsigned NumArgOperands = FuncletPad.arg_size();
3157 Vals.push_back(NumArgOperands);
3158 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
3159 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
3160 break;
3161 }
3162 case Instruction::CatchSwitch: {
3164 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
3165
3166 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3167
3168 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3169 Vals.push_back(NumHandlers);
3170 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3171 Vals.push_back(VE.getValueID(CatchPadBB));
3172
3173 if (CatchSwitch.hasUnwindDest())
3174 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3175 break;
3176 }
3177 case Instruction::CallBr: {
3178 const CallBrInst *CBI = cast<CallBrInst>(&I);
3179 const Value *Callee = CBI->getCalledOperand();
3180 FunctionType *FTy = CBI->getFunctionType();
3181
3182 if (CBI->hasOperandBundles())
3183 writeOperandBundles(*CBI, InstID);
3184
3186
3188
3191
3192 Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3193 Vals.push_back(CBI->getNumIndirectDests());
3194 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3195 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3196
3197 Vals.push_back(VE.getTypeID(FTy));
3198 pushValueAndType(Callee, InstID, Vals);
3199
3200 // Emit value #'s for the fixed parameters.
3201 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3202 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3203
3204 // Emit type/value pairs for varargs params.
3205 if (FTy->isVarArg()) {
3206 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3207 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3208 }
3209 break;
3210 }
3211 case Instruction::Unreachable:
3213 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3214 break;
3215
3216 case Instruction::PHI: {
3217 const PHINode &PN = cast<PHINode>(I);
3219 // With the newer instruction encoding, forward references could give
3220 // negative valued IDs. This is most common for PHIs, so we use
3221 // signed VBRs.
3223 Vals64.push_back(VE.getTypeID(PN.getType()));
3224 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3225 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3226 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3227 }
3228
3230 if (Flags != 0)
3231 Vals64.push_back(Flags);
3232
3233 // Emit a Vals64 vector and exit.
3234 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3235 Vals64.clear();
3236 return;
3237 }
3238
3239 case Instruction::LandingPad: {
3240 const LandingPadInst &LP = cast<LandingPadInst>(I);
3242 Vals.push_back(VE.getTypeID(LP.getType()));
3243 Vals.push_back(LP.isCleanup());
3244 Vals.push_back(LP.getNumClauses());
3245 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3246 if (LP.isCatch(I))
3248 else
3250 pushValueAndType(LP.getClause(I), InstID, Vals);
3251 }
3252 break;
3253 }
3254
3255 case Instruction::Alloca: {
3257 const AllocaInst &AI = cast<AllocaInst>(I);
3258 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3259 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3260 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3261 using APV = AllocaPackedValues;
3262 unsigned Record = 0;
3263 unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3264 Bitfield::set<APV::AlignLower>(
3265 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3266 Bitfield::set<APV::AlignUpper>(Record,
3267 EncodedAlign >> APV::AlignLower::Bits);
3268 Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3269 Bitfield::set<APV::ExplicitType>(Record, true);
3270 Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3271 Vals.push_back(Record);
3272
3273 unsigned AS = AI.getAddressSpace();
3274 if (AS != M.getDataLayout().getAllocaAddrSpace())
3275 Vals.push_back(AS);
3276 break;
3277 }
3278
3279 case Instruction::Load:
3280 if (cast<LoadInst>(I).isAtomic()) {
3282 pushValueAndType(I.getOperand(0), InstID, Vals);
3283 } else {
3285 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3286 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3287 }
3288 Vals.push_back(VE.getTypeID(I.getType()));
3289 Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3290 Vals.push_back(cast<LoadInst>(I).isVolatile());
3291 if (cast<LoadInst>(I).isAtomic()) {
3292 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3293 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3294 }
3295 break;
3296 case Instruction::Store:
3297 if (cast<StoreInst>(I).isAtomic())
3299 else
3301 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
3302 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3303 Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3304 Vals.push_back(cast<StoreInst>(I).isVolatile());
3305 if (cast<StoreInst>(I).isAtomic()) {
3306 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3307 Vals.push_back(
3308 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3309 }
3310 break;
3311 case Instruction::AtomicCmpXchg:
3313 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3314 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3315 pushValue(I.getOperand(2), InstID, Vals); // newval.
3316 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3317 Vals.push_back(
3318 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3319 Vals.push_back(
3320 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3321 Vals.push_back(
3322 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3323 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3324 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3325 break;
3326 case Instruction::AtomicRMW:
3328 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3329 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3330 Vals.push_back(
3331 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
3332 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3333 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3334 Vals.push_back(
3335 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3336 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3337 break;
3338 case Instruction::Fence:
3340 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3341 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3342 break;
3343 case Instruction::Call: {
3344 const CallInst &CI = cast<CallInst>(I);
3345 FunctionType *FTy = CI.getFunctionType();
3346
3347 if (CI.hasOperandBundles())
3348 writeOperandBundles(CI, InstID);
3349
3351
3353
3354 unsigned Flags = getOptimizationFlags(&I);
3356 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3357 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3359 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3360 unsigned(Flags != 0) << bitc::CALL_FMF);
3361 if (Flags != 0)
3362 Vals.push_back(Flags);
3363
3364 Vals.push_back(VE.getTypeID(FTy));
3365 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3366
3367 // Emit value #'s for the fixed parameters.
3368 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3369 // Check for labels (can happen with asm labels).
3370 if (FTy->getParamType(i)->isLabelTy())
3371 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
3372 else
3373 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3374 }
3375
3376 // Emit type/value pairs for varargs params.
3377 if (FTy->isVarArg()) {
3378 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3379 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3380 }
3381 break;
3382 }
3383 case Instruction::VAArg:
3385 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3386 pushValue(I.getOperand(0), InstID, Vals); // valist.
3387 Vals.push_back(VE.getTypeID(I.getType())); // restype.
3388 break;
3389 case Instruction::Freeze:
3391 pushValueAndType(I.getOperand(0), InstID, Vals);
3392 break;
3393 }
3394
3395 Stream.EmitRecord(Code, Vals, AbbrevToUse);
3396 Vals.clear();
3397}
3398
3399/// Write a GlobalValue VST to the module. The purpose of this data structure is
3400/// to allow clients to efficiently find the function body.
3401void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3402 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3403 // Get the offset of the VST we are writing, and backpatch it into
3404 // the VST forward declaration record.
3405 uint64_t VSTOffset = Stream.GetCurrentBitNo();
3406 // The BitcodeStartBit was the stream offset of the identification block.
3407 VSTOffset -= bitcodeStartBit();
3408 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3409 // Note that we add 1 here because the offset is relative to one word
3410 // before the start of the identification block, which was historically
3411 // always the start of the regular bitcode header.
3412 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3413
3415
3416 auto Abbv = std::make_shared<BitCodeAbbrev>();
3418 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3419 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3420 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3421
3422 for (const Function &F : M) {
3423 uint64_t Record[2];
3424
3425 if (F.isDeclaration())
3426 continue;
3427
3428 Record[0] = VE.getValueID(&F);
3429
3430 // Save the word offset of the function (from the start of the
3431 // actual bitcode written to the stream).
3432 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3433 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3434 // Note that we add 1 here because the offset is relative to one word
3435 // before the start of the identification block, which was historically
3436 // always the start of the regular bitcode header.
3437 Record[1] = BitcodeIndex / 32 + 1;
3438
3439 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3440 }
3441
3442 Stream.ExitBlock();
3443}
3444
3445/// Emit names for arguments, instructions and basic blocks in a function.
3446void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3447 const ValueSymbolTable &VST) {
3448 if (VST.empty())
3449 return;
3450
3452
3453 // FIXME: Set up the abbrev, we know how many values there are!
3454 // FIXME: We know if the type names can use 7-bit ascii.
3456
3457 for (const ValueName &Name : VST) {
3458 // Figure out the encoding to use for the name.
3460
3461 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3462 NameVals.push_back(VE.getValueID(Name.getValue()));
3463
3464 // VST_CODE_ENTRY: [valueid, namechar x N]
3465 // VST_CODE_BBENTRY: [bbid, namechar x N]
3466 unsigned Code;
3467 if (isa<BasicBlock>(Name.getValue())) {
3469 if (Bits == SE_Char6)
3470 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3471 } else {
3473 if (Bits == SE_Char6)
3474 AbbrevToUse = VST_ENTRY_6_ABBREV;
3475 else if (Bits == SE_Fixed7)
3476 AbbrevToUse = VST_ENTRY_7_ABBREV;
3477 }
3478
3479 for (const auto P : Name.getKey())
3480 NameVals.push_back((unsigned char)P);
3481
3482 // Emit the finished record.
3483 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3484 NameVals.clear();
3485 }
3486
3487 Stream.ExitBlock();
3488}
3489
3490void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3491 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3492 unsigned Code;
3493 if (isa<BasicBlock>(Order.V))
3495 else
3497
3498 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3499 Record.push_back(VE.getValueID(Order.V));
3500 Stream.EmitRecord(Code, Record);
3501}
3502
3503void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3505 "Expected to be preserving use-list order");
3506
3507 auto hasMore = [&]() {
3508 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3509 };
3510 if (!hasMore())
3511 // Nothing to do.
3512 return;
3513
3515 while (hasMore()) {
3516 writeUseList(std::move(VE.UseListOrders.back()));
3517 VE.UseListOrders.pop_back();
3518 }
3519 Stream.ExitBlock();
3520}
3521
3522/// Emit a function body to the module stream.
3523void ModuleBitcodeWriter::writeFunction(
3524 const Function &F,
3525 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3526 // Save the bitcode index of the start of this function block for recording
3527 // in the VST.
3528 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3529
3532
3534
3535 // Emit the number of basic blocks, so the reader can create them ahead of
3536 // time.
3537 Vals.push_back(VE.getBasicBlocks().size());
3539 Vals.clear();
3540
3541 // If there are function-local constants, emit them now.
3542 unsigned CstStart, CstEnd;
3543 VE.getFunctionConstantRange(CstStart, CstEnd);
3544 writeConstants(CstStart, CstEnd, false);
3545
3546 // If there is function-local metadata, emit it now.
3547 writeFunctionMetadata(F);
3548
3549 // Keep a running idea of what the instruction ID is.
3550 unsigned InstID = CstEnd;
3551
3552 bool NeedsMetadataAttachment = F.hasMetadata();
3553
3554 DILocation *LastDL = nullptr;
3555 SmallSetVector<Function *, 4> BlockAddressUsers;
3556
3557 // Finally, emit all the instructions, in order.
3558 for (const BasicBlock &BB : F) {
3559 for (const Instruction &I : BB) {
3560 writeInstruction(I, InstID, Vals);
3561
3562 if (!I.getType()->isVoidTy())
3563 ++InstID;
3564
3565 // If the instruction has metadata, write a metadata attachment later.
3566 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3567
3568 // If the instruction has a debug location, emit it.
3569 if (DILocation *DL = I.getDebugLoc()) {
3570 if (DL == LastDL) {
3571 // Just repeat the same debug loc as last time.
3573 } else {
3574 Vals.push_back(DL->getLine());
3575 Vals.push_back(DL->getColumn());
3576 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3577 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3578 Vals.push_back(DL->isImplicitCode());
3580 Vals.clear();
3581 LastDL = DL;
3582 }
3583 }
3584
3585 // If the instruction has DbgRecords attached to it, emit them. Note that
3586 // they come after the instruction so that it's easy to attach them again
3587 // when reading the bitcode, even though conceptually the debug locations
3588 // start "before" the instruction.
3589 if (I.hasDbgRecords() && WriteNewDbgInfoFormatToBitcode) {
3590 /// Try to push the value only (unwrapped), otherwise push the
3591 /// metadata wrapped value. Returns true if the value was pushed
3592 /// without the ValueAsMetadata wrapper.
3593 auto PushValueOrMetadata = [&Vals, InstID,
3594 this](Metadata *RawLocation) {
3595 assert(RawLocation &&
3596 "RawLocation unexpectedly null in DbgVariableRecord");
3597 if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) {
3598 SmallVector<unsigned, 2> ValAndType;
3599 // If the value is a fwd-ref the type is also pushed. We don't
3600 // want the type, so fwd-refs are kept wrapped (pushValueAndType
3601 // returns false if the value is pushed without type).
3602 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
3603 Vals.push_back(ValAndType[0]);
3604 return true;
3605 }
3606 }
3607 // The metadata is a DIArgList, or ValueAsMetadata wrapping a
3608 // fwd-ref. Push the metadata ID.
3609 Vals.push_back(VE.getMetadataID(RawLocation));
3610 return false;
3611 };
3612
3613 // Write out non-instruction debug information attached to this
3614 // instruction. Write it after the instruction so that it's easy to
3615 // re-attach to the instruction reading the records in.
3616 for (DbgRecord &DR : I.DebugMarker->getDbgRecordRange()) {
3617 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
3618 Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc()));
3619 Vals.push_back(VE.getMetadataID(DLR->getLabel()));
3621 Vals.clear();
3622 continue;
3623 }
3624
3625 // First 3 fields are common to all kinds:
3626 // DILocation, DILocalVariable, DIExpression
3627 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
3628 // ..., LocationMetadata
3629 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
3630 // ..., Value
3631 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
3632 // ..., LocationMetadata
3633 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
3634 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
3635 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
3636 Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc()));
3637 Vals.push_back(VE.getMetadataID(DVR.getVariable()));
3638 Vals.push_back(VE.getMetadataID(DVR.getExpression()));
3639 if (DVR.isDbgValue()) {
3640 if (PushValueOrMetadata(DVR.getRawLocation()))
3642 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
3643 else
3645 } else if (DVR.isDbgDeclare()) {
3646 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3648 } else {
3649 assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind");
3650 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3651 Vals.push_back(VE.getMetadataID(DVR.getAssignID()));
3653 Vals.push_back(VE.getMetadataID(DVR.getRawAddress()));
3655 }
3656 Vals.clear();
3657 }
3658 }
3659 }
3660
3661 if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
3662 SmallVector<Value *> Worklist{BA};
3663 SmallPtrSet<Value *, 8> Visited{BA};
3664 while (!Worklist.empty()) {
3665 Value *V = Worklist.pop_back_val();
3666 for (User *U : V->users()) {
3667 if (auto *I = dyn_cast<Instruction>(U)) {
3668 Function *P = I->getFunction();
3669 if (P != &F)
3670 BlockAddressUsers.insert(P);
3671 } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
3672 Visited.insert(U).second)
3673 Worklist.push_back(U);
3674 }
3675 }
3676 }
3677 }
3678
3679 if (!BlockAddressUsers.empty()) {
3680 Vals.resize(BlockAddressUsers.size());
3681 for (auto I : llvm::enumerate(BlockAddressUsers))
3682 Vals[I.index()] = VE.getValueID(I.value());
3684 Vals.clear();
3685 }
3686
3687 // Emit names for all the instructions etc.
3688 if (auto *Symtab = F.getValueSymbolTable())
3689 writeFunctionLevelValueSymbolTable(*Symtab);
3690
3691 if (NeedsMetadataAttachment)
3692 writeFunctionMetadataAttachment(F);
3694 writeUseListBlock(&F);
3695 VE.purgeFunction();
3696 Stream.ExitBlock();
3697}
3698
3699// Emit blockinfo, which defines the standard abbreviations etc.
3700void ModuleBitcodeWriter::writeBlockInfo() {
3701 // We only want to emit block info records for blocks that have multiple
3702 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3703 // Other blocks can define their abbrevs inline.
3704 Stream.EnterBlockInfoBlock();
3705
3706 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3707 auto Abbv = std::make_shared<BitCodeAbbrev>();
3713 VST_ENTRY_8_ABBREV)
3714 llvm_unreachable("Unexpected abbrev ordering!");
3715 }
3716
3717 { // 7-bit fixed width VST_CODE_ENTRY strings.
3718 auto Abbv = std::make_shared<BitCodeAbbrev>();
3724 VST_ENTRY_7_ABBREV)
3725 llvm_unreachable("Unexpected abbrev ordering!");
3726 }
3727 { // 6-bit char6 VST_CODE_ENTRY strings.
3728 auto Abbv = std::make_shared<BitCodeAbbrev>();
3734 VST_ENTRY_6_ABBREV)
3735 llvm_unreachable("Unexpected abbrev ordering!");
3736 }
3737 { // 6-bit char6 VST_CODE_BBENTRY strings.
3738 auto Abbv = std::make_shared<BitCodeAbbrev>();
3744 VST_BBENTRY_6_ABBREV)
3745 llvm_unreachable("Unexpected abbrev ordering!");
3746 }
3747
3748 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3749 auto Abbv = std::make_shared<BitCodeAbbrev>();
3754 CONSTANTS_SETTYPE_ABBREV)
3755 llvm_unreachable("Unexpected abbrev ordering!");
3756 }
3757
3758 { // INTEGER abbrev for CONSTANTS_BLOCK.
3759 auto Abbv = std::make_shared<BitCodeAbbrev>();
3763 CONSTANTS_INTEGER_ABBREV)
3764 llvm_unreachable("Unexpected abbrev ordering!");
3765 }
3766
3767 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3768 auto Abbv = std::make_shared<BitCodeAbbrev>();
3770 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3771 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3773 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3774
3776 CONSTANTS_CE_CAST_Abbrev)
3777 llvm_unreachable("Unexpected abbrev ordering!");
3778 }
3779 { // NULL abbrev for CONSTANTS_BLOCK.
3780 auto Abbv = std::make_shared<BitCodeAbbrev>();
3783 CONSTANTS_NULL_Abbrev)
3784 llvm_unreachable("Unexpected abbrev ordering!");
3785 }
3786
3787 // FIXME: This should only use space for first class types!
3788
3789 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3790 auto Abbv = std::make_shared<BitCodeAbbrev>();
3792 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3793 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3795 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3796 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3797 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3798 FUNCTION_INST_LOAD_ABBREV)
3799 llvm_unreachable("Unexpected abbrev ordering!");
3800 }
3801 { // INST_UNOP abbrev for FUNCTION_BLOCK.
3802 auto Abbv = std::make_shared<BitCodeAbbrev>();
3804 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3805 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3806 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3807 FUNCTION_INST_UNOP_ABBREV)
3808 llvm_unreachable("Unexpected abbrev ordering!");
3809 }
3810 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3811 auto Abbv = std::make_shared<BitCodeAbbrev>();
3813 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3814 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3815 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3816 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3817 FUNCTION_INST_UNOP_FLAGS_ABBREV)
3818 llvm_unreachable("Unexpected abbrev ordering!");
3819 }
3820 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3821 auto Abbv = std::make_shared<BitCodeAbbrev>();
3823 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3824 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3825 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3826 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3827 FUNCTION_INST_BINOP_ABBREV)
3828 llvm_unreachable("Unexpected abbrev ordering!");
3829 }
3830 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3831 auto Abbv = std::make_shared<BitCodeAbbrev>();
3833 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3834 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3835 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3836 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3837 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3838 FUNCTION_INST_BINOP_FLAGS_ABBREV)
3839 llvm_unreachable("Unexpected abbrev ordering!");
3840 }
3841 { // INST_CAST abbrev for FUNCTION_BLOCK.
3842 auto Abbv = std::make_shared<BitCodeAbbrev>();
3844 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3845 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3847 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3848 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3849 FUNCTION_INST_CAST_ABBREV)
3850 llvm_unreachable("Unexpected abbrev ordering!");
3851 }
3852 { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
3853 auto Abbv = std::make_shared<BitCodeAbbrev>();
3855 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3856 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3858 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3859 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3860 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3861 FUNCTION_INST_CAST_FLAGS_ABBREV)
3862 llvm_unreachable("Unexpected abbrev ordering!");
3863 }
3864
3865 { // INST_RET abbrev for FUNCTION_BLOCK.
3866 auto Abbv = std::make_shared<BitCodeAbbrev>();
3868 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3869 FUNCTION_INST_RET_VOID_ABBREV)
3870 llvm_unreachable("Unexpected abbrev ordering!");
3871 }
3872 { // INST_RET abbrev for FUNCTION_BLOCK.
3873 auto Abbv = std::make_shared<BitCodeAbbrev>();
3875 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3876 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3877 FUNCTION_INST_RET_VAL_ABBREV)
3878 llvm_unreachable("Unexpected abbrev ordering!");
3879 }
3880 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3881 auto Abbv = std::make_shared<BitCodeAbbrev>();
3883 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3884 FUNCTION_INST_UNREACHABLE_ABBREV)
3885 llvm_unreachable("Unexpected abbrev ordering!");
3886 }
3887 {
3888 auto Abbv = std::make_shared<BitCodeAbbrev>();
3891 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3892 Log2_32_Ceil(VE.getTypes().size() + 1)));
3895 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3896 FUNCTION_INST_GEP_ABBREV)
3897 llvm_unreachable("Unexpected abbrev ordering!");
3898 }
3899 {
3900 auto Abbv = std::make_shared<BitCodeAbbrev>();
3902 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc
3903 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var
3904 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr
3905 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // val
3906 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3907 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
3908 llvm_unreachable("Unexpected abbrev ordering! 1");
3909 }
3910 Stream.ExitBlock();
3911}
3912
3913/// Write the module path strings, currently only used when generating
3914/// a combined index file.
3915void IndexBitcodeWriter::writeModStrings() {
3917
3918 // TODO: See which abbrev sizes we actually need to emit
3919
3920 // 8-bit fixed-width MST_ENTRY strings.
3921 auto Abbv = std::make_shared<BitCodeAbbrev>();
3926 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3927
3928 // 7-bit fixed width MST_ENTRY strings.
3929 Abbv = std::make_shared<BitCodeAbbrev>();
3934 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3935
3936 // 6-bit char6 MST_ENTRY strings.
3937 Abbv = std::make_shared<BitCodeAbbrev>();
3942 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3943
3944 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3945 Abbv = std::make_shared<BitCodeAbbrev>();
3952 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3953
3955 forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
3956 StringRef Key = MPSE.getKey();
3957 const auto &Hash = MPSE.getValue();
3959 unsigned AbbrevToUse = Abbrev8Bit;
3960 if (Bits == SE_Char6)
3961 AbbrevToUse = Abbrev6Bit;
3962 else if (Bits == SE_Fixed7)
3963 AbbrevToUse = Abbrev7Bit;
3964
3965 auto ModuleId = ModuleIdMap.size();
3966 ModuleIdMap[Key] = ModuleId;
3967 Vals.push_back(ModuleId);
3968 Vals.append(Key.begin(), Key.end());
3969
3970 // Emit the finished record.
3971 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3972
3973 // Emit an optional hash for the module now
3974 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3975 Vals.assign(Hash.begin(), Hash.end());
3976 // Emit the hash record.
3977 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3978 }
3979
3980 Vals.clear();
3981 });
3982 Stream.ExitBlock();
3983}
3984
3985/// Write the function type metadata related records that need to appear before
3986/// a function summary entry (whether per-module or combined).
3987template <typename Fn>
3989 FunctionSummary *FS,
3990 Fn GetValueID) {
3991 if (!FS->type_tests().empty())
3992 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3993
3995
3996 auto WriteVFuncIdVec = [&](uint64_t Ty,
3998 if (VFs.empty())
3999 return;
4000 Record.clear();
4001 for (auto &VF : VFs) {
4002 Record.push_back(VF.GUID);
4003 Record.push_back(VF.Offset);
4004 }
4005 Stream.EmitRecord(Ty, Record);
4006 };
4007
4008 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
4009 FS->type_test_assume_vcalls());
4010 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
4011 FS->type_checked_load_vcalls());
4012
4013 auto WriteConstVCallVec = [&](uint64_t Ty,
4015 for (auto &VC : VCs) {
4016 Record.clear();
4017 Record.push_back(VC.VFunc.GUID);
4018 Record.push_back(VC.VFunc.Offset);
4019 llvm::append_range(Record, VC.Args);
4020 Stream.EmitRecord(Ty, Record);
4021 }
4022 };
4023
4024 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
4025 FS->type_test_assume_const_vcalls());
4026 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
4027 FS->type_checked_load_const_vcalls());
4028
4029 auto WriteRange = [&](ConstantRange Range) {
4031 assert(Range.getLower().getNumWords() == 1);
4032 assert(Range.getUpper().getNumWords() == 1);
4035 };
4036
4037 if (!FS->paramAccesses().empty()) {
4038 Record.clear();
4039 for (auto &Arg : FS->paramAccesses()) {
4040 size_t UndoSize = Record.size();
4041 Record.push_back(Arg.ParamNo);
4042 WriteRange(Arg.Use);
4043 Record.push_back(Arg.Calls.size());
4044 for (auto &Call : Arg.Calls) {
4045 Record.push_back(Call.ParamNo);
4046 std::optional<unsigned> ValueID = GetValueID(Call.Callee);
4047 if (!ValueID) {
4048 // If ValueID is unknown we can't drop just this call, we must drop
4049 // entire parameter.
4050 Record.resize(UndoSize);
4051 break;
4052 }
4053 Record.push_back(*ValueID);
4054 WriteRange(Call.Offsets);
4055 }
4056 }
4057 if (!Record.empty())
4059 }
4060}
4061
4062/// Collect type IDs from type tests used by function.
4063static void
4065 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4066 if (!FS->type_tests().empty())
4067 for (auto &TT : FS->type_tests())
4068 ReferencedTypeIds.insert(TT);
4069
4070 auto GetReferencedTypesFromVFuncIdVec =
4072 for (auto &VF : VFs)
4073 ReferencedTypeIds.insert(VF.GUID);
4074 };
4075
4076 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4077 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4078
4079 auto GetReferencedTypesFromConstVCallVec =
4081 for (auto &VC : VCs)
4082 ReferencedTypeIds.insert(VC.VFunc.GUID);
4083 };
4084
4085 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4086 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4087}
4088
4090 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
4092 NameVals.push_back(args.size());
4093 llvm::append_range(NameVals, args);
4094
4095 NameVals.push_back(ByArg.TheKind);
4096 NameVals.push_back(ByArg.Info);
4097 NameVals.push_back(ByArg.Byte);
4098 NameVals.push_back(ByArg.Bit);
4099}
4100
4102 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4103 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
4104 NameVals.push_back(Id);
4105
4106 NameVals.push_back(Wpd.TheKind);
4107 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
4108 NameVals.push_back(Wpd.SingleImplName.size());
4109
4110 NameVals.push_back(Wpd.ResByArg.size());
4111 for (auto &A : Wpd.ResByArg)
4112 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
4113}
4114
4116 StringTableBuilder &StrtabBuilder,
4117 const std::string &Id,
4118 const TypeIdSummary &Summary) {
4119 NameVals.push_back(StrtabBuilder.add(Id));
4120 NameVals.push_back(Id.size());
4121
4122 NameVals.push_back(Summary.TTRes.TheKind);
4123 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
4124 NameVals.push_back(Summary.TTRes.AlignLog2);
4125 NameVals.push_back(Summary.TTRes.SizeM1);
4126 NameVals.push_back(Summary.TTRes.BitMask);
4127 NameVals.push_back(Summary.TTRes.InlineBits);
4128
4129 for (auto &W : Summary.WPDRes)
4130 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
4131 W.second);
4132}
4133
4135 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4136 const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
4137 ValueEnumerator &VE) {
4138 NameVals.push_back(StrtabBuilder.add(Id));
4139 NameVals.push_back(Id.size());
4140
4141 for (auto &P : Summary) {
4142 NameVals.push_back(P.AddressPointOffset);
4143 NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
4144 }
4145}
4146
4148 BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
4149 unsigned AllocAbbrev, bool PerModule,
4150 std::function<unsigned(const ValueInfo &VI)> GetValueID,
4151 std::function<unsigned(unsigned)> GetStackIndex) {
4153
4154 for (auto &CI : FS->callsites()) {
4155 Record.clear();
4156 // Per module callsite clones should always have a single entry of
4157 // value 0.
4158 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4159 Record.push_back(GetValueID(CI.Callee));
4160 if (!PerModule) {
4161 Record.push_back(CI.StackIdIndices.size());
4162 Record.push_back(CI.Clones.size());
4163 }
4164 for (auto Id : CI.StackIdIndices)
4165 Record.push_back(GetStackIndex(Id));
4166 if (!PerModule) {
4167 for (auto V : CI.Clones)
4168 Record.push_back(V);
4169 }
4172 Record, CallsiteAbbrev);
4173 }
4174
4175 for (auto &AI : FS->allocs()) {
4176 Record.clear();
4177 // Per module alloc versions should always have a single entry of
4178 // value 0.
4179 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4180 if (!PerModule) {
4181 Record.push_back(AI.MIBs.size());
4182 Record.push_back(AI.Versions.size());
4183 }
4184 for (auto &MIB : AI.MIBs) {
4185 Record.push_back((uint8_t)MIB.AllocType);
4186 Record.push_back(MIB.StackIdIndices.size());
4187 for (auto Id : MIB.StackIdIndices)
4188 Record.push_back(GetStackIndex(Id));
4189 }
4190 if (!PerModule) {
4191 for (auto V : AI.Versions)
4192 Record.push_back(V);
4193 }
4194 Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_ALLOC_INFO
4196 Record, AllocAbbrev);
4197 }
4198}
4199
4200// Helper to emit a single function summary record.
4201void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4203 unsigned ValueID, unsigned FSCallsRelBFAbbrev,
4204 unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
4205 unsigned AllocAbbrev, const Function &F) {
4206 NameVals.push_back(ValueID);
4207
4208 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4209
4211 Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
4212 return {VE.getValueID(VI.getValue())};
4213 });
4214
4216 Stream, FS, CallsiteAbbrev, AllocAbbrev,
4217 /*PerModule*/ true,
4218 /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
4219 /*GetStackIndex*/ [&](unsigned I) { return I; });
4220
4221 auto SpecialRefCnts = FS->specialRefCounts();
4222 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4223 NameVals.push_back(FS->instCount());
4224 NameVals.push_back(getEncodedFFlags(FS->fflags()));
4225 NameVals.push_back(FS->refs().size());
4226 NameVals.push_back(SpecialRefCnts.first); // rorefcnt
4227 NameVals.push_back(SpecialRefCnts.second); // worefcnt
4228
4229 for (auto &RI : FS->refs())
4230 NameVals.push_back(getValueId(RI));
4231
4232 const bool UseRelBFRecord =
4233 WriteRelBFToSummary && !F.hasProfileData() &&
4235 for (auto &ECI : FS->calls()) {
4236 NameVals.push_back(getValueId(ECI.first));
4237 if (UseRelBFRecord)
4238 NameVals.push_back(getEncodedRelBFCallEdgeInfo(ECI.second));
4239 else
4240 NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));
4241 }
4242
4243 unsigned FSAbbrev =
4244 (UseRelBFRecord ? FSCallsRelBFAbbrev : FSCallsProfileAbbrev);
4245 unsigned Code =
4247
4248 // Emit the finished record.
4249 Stream.EmitRecord(Code, NameVals, FSAbbrev);
4250 NameVals.clear();
4251}
4252
4253// Collect the global value references in the given variable's initializer,
4254// and emit them in a summary record.
4255void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4256 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4257 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
4258 auto VI = Index->getValueInfo(V.getGUID());
4259 if (!VI || VI.getSummaryList().empty()) {
4260 // Only declarations should not have a summary (a declaration might however
4261 // have a summary if the def was in module level asm).
4262 assert(V.isDeclaration());
4263 return;
4264 }
4265 auto *Summary = VI.getSummaryList()[0].get();
4266 NameVals.push_back(VE.getValueID(&V));
4267 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
4268 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4269 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4270
4271 auto VTableFuncs = VS->vTableFuncs();
4272 if (!VTableFuncs.empty())
4273 NameVals.push_back(VS->refs().size());
4274
4275 unsigned SizeBeforeRefs = NameVals.size();
4276 for (auto &RI : VS->refs())
4277 NameVals.push_back(VE.getValueID(RI.getValue()));
4278 // Sort the refs for determinism output, the vector returned by FS->refs() has
4279 // been initialized from a DenseSet.
4280 llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
4281
4282 if (VTableFuncs.empty())
4284 FSModRefsAbbrev);
4285 else {
4286 // VTableFuncs pairs should already be sorted by offset.
4287 for (auto &P : VTableFuncs) {
4288 NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
4289 NameVals.push_back(P.VTableOffset);
4290 }
4291
4293 FSModVTableRefsAbbrev);
4294 }
4295 NameVals.clear();
4296}
4297
4298/// Emit the per-module summary section alongside the rest of
4299/// the module's bitcode.
4300void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4301 // By default we compile with ThinLTO if the module has a summary, but the
4302 // client can request full LTO with a module flag.
4303 bool IsThinLTO = true;
4304 if (auto *MD =
4305 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
4306 IsThinLTO = MD->getZExtValue();
4309 4);
4310
4311 Stream.EmitRecord(
4314
4315 // Write the index flags.
4316 uint64_t Flags = 0;
4317 // Bits 1-3 are set only in the combined index, skip them.
4318 if (Index->enableSplitLTOUnit())
4319 Flags |= 0x8;
4320 if (Index->hasUnifiedLTO())
4321 Flags |= 0x200;
4322
4324
4325 if (Index->begin() == Index->end()) {
4326 Stream.ExitBlock();
4327 return;
4328 }
4329
4330 for (const auto &GVI : valueIds()) {
4332 ArrayRef<uint64_t>{GVI.second, GVI.first});
4333 }
4334
4335 if (!Index->stackIds().empty()) {
4336 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4337 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4338 // numids x stackid
4339 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4340 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4341 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4342 Stream.EmitRecord(bitc::FS_STACK_IDS, Index->stackIds(), StackIdAbbvId);
4343 }
4344
4345 // Abbrev for FS_PERMODULE_PROFILE.
4346 auto Abbv = std::make_shared<BitCodeAbbrev>();
4348 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4349 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags
4350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4352 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4353 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4354 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4355 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4358 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4359
4360 // Abbrev for FS_PERMODULE_RELBF.
4361 Abbv = std::make_shared<BitCodeAbbrev>();
4363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4369 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4370 // numrefs x valueid, n x (valueid, rel_block_freq+tailcall])
4373 unsigned FSCallsRelBFAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4374
4375 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4376 Abbv = std::make_shared<BitCodeAbbrev>();
4378 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4379 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4380 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4382 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4383
4384 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4385 Abbv = std::make_shared<BitCodeAbbrev>();
4387 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4388 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4389 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4390 // numrefs x valueid, n x (valueid , offset)
4393 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4394
4395 // Abbrev for FS_ALIAS.
4396 Abbv = std::make_shared<BitCodeAbbrev>();
4397 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4398 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4399 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4400 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4401 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4402
4403 // Abbrev for FS_TYPE_ID_METADATA
4404 Abbv = std::make_shared<BitCodeAbbrev>();
4406 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4407 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4408 // n x (valueid , offset)
4411 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4412
4413 Abbv = std::make_shared<BitCodeAbbrev>();
4415 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4416 // n x stackidindex
4419 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4420
4421 Abbv = std::make_shared<BitCodeAbbrev>();
4423 // n x (alloc type, numstackids, numstackids x stackidindex)
4426 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4427
4429 // Iterate over the list of functions instead of the Index to
4430 // ensure the ordering is stable.
4431 for (const Function &F : M) {
4432 // Summary emission does not support anonymous functions, they have to
4433 // renamed using the anonymous function renaming pass.
4434 if (!F.hasName())
4435 report_fatal_error("Unexpected anonymous function when writing summary");
4436
4437 ValueInfo VI = Index->getValueInfo(F.getGUID());
4438 if (!VI || VI.getSummaryList().empty()) {
4439 // Only declarations should not have a summary (a declaration might
4440 // however have a summary if the def was in module level asm).
4441 assert(F.isDeclaration());
4442 continue;
4443 }
4444 auto *Summary = VI.getSummaryList()[0].get();
4445 writePerModuleFunctionSummaryRecord(
4446 NameVals, Summary, VE.getValueID(&F), FSCallsRelBFAbbrev,
4447 FSCallsProfileAbbrev, CallsiteAbbrev, AllocAbbrev, F);
4448 }
4449
4450 // Capture references from GlobalVariable initializers, which are outside
4451 // of a function scope.
4452 for (const GlobalVariable &G : M.globals())
4453 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4454 FSModVTableRefsAbbrev);
4455
4456 for (const GlobalAlias &A : M.aliases()) {
4457 auto *Aliasee = A.getAliaseeObject();
4458 // Skip ifunc and nameless functions which don't have an entry in the
4459 // summary.
4460 if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
4461 continue;
4462 auto AliasId = VE.getValueID(&A);
4463 auto AliaseeId = VE.getValueID(Aliasee);
4464 NameVals.push_back(AliasId);
4465 auto *Summary = Index->getGlobalValueSummary(A);
4466 AliasSummary *AS = cast<AliasSummary>(Summary);
4467 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4468 NameVals.push_back(AliaseeId);
4469 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4470 NameVals.clear();
4471 }
4472
4473 for (auto &S : Index->typeIdCompatibleVtableMap()) {
4474 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4475 S.second, VE);
4476 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4477 TypeIdCompatibleVtableAbbrev);
4478 NameVals.clear();
4479 }
4480
4481 if (Index->getBlockCount())
4483 ArrayRef<uint64_t>{Index->getBlockCount()});
4484
4485 Stream.ExitBlock();
4486}
4487
4488/// Emit the combined summary section into the combined index file.
4489void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4491 Stream.EmitRecord(
4494
4495 // Write the index flags.
4497
4498 for (const auto &GVI : valueIds()) {
4500 ArrayRef<uint64_t>{GVI.second, GVI.first});
4501 }
4502
4503 // Write the stack ids used by this index, which will be a subset of those in
4504 // the full index in the case of distributed indexes.
4505 if (!StackIds.empty()) {
4506 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4507 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4508 // numids x stackid
4509 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4510 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4511 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4512 Stream.EmitRecord(bitc::FS_STACK_IDS, StackIds, StackIdAbbvId);
4513 }
4514
4515 // Abbrev for FS_COMBINED_PROFILE.
4516 auto Abbv = std::make_shared<BitCodeAbbrev>();
4518 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4519 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4520 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4521 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4522 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4523 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
4524 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4525 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4526 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4527 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4530 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4531
4532 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
4533 Abbv = std::make_shared<BitCodeAbbrev>();
4535 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4536 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4537 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4538 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4540 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4541
4542 // Abbrev for FS_COMBINED_ALIAS.
4543 Abbv = std::make_shared<BitCodeAbbrev>();
4545 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4546 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4547 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4548 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4549 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4550
4551 Abbv = std::make_shared<BitCodeAbbrev>();
4553 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4554 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices
4555 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
4556 // numstackindices x stackidindex, numver x version
4559 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4560
4561 Abbv = std::make_shared<BitCodeAbbrev>();
4563 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
4564 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
4565 // nummib x (alloc type, numstackids, numstackids x stackidindex),
4566 // numver x version
4569 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4570
4571 // The aliases are emitted as a post-pass, and will point to the value
4572 // id of the aliasee. Save them in a vector for post-processing.
4574
4575 // Save the value id for each summary for alias emission.
4577
4579
4580 // Set that will be populated during call to writeFunctionTypeMetadataRecords
4581 // with the type ids referenced by this index file.
4582 std::set<GlobalValue::GUID> ReferencedTypeIds;
4583
4584 // For local linkage, we also emit the original name separately
4585 // immediately after the record.
4586 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
4587 // We don't need to emit the original name if we are writing the index for
4588 // distributed backends (in which case ModuleToSummariesForIndex is
4589 // non-null). The original name is only needed during the thin link, since
4590 // for SamplePGO the indirect call targets for local functions have
4591 // have the original name annotated in profile.
4592 // Continue to emit it when writing out the entire combined index, which is
4593 // used in testing the thin link via llvm-lto.
4594 if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
4595 return;
4596 NameVals.push_back(S.getOriginalName());
4598 NameVals.clear();
4599 };
4600
4601 std::set<GlobalValue::GUID> DefOrUseGUIDs;
4602 forEachSummary([&](GVInfo I, bool IsAliasee) {
4603 GlobalValueSummary *S = I.second;
4604 assert(S);
4605 DefOrUseGUIDs.insert(I.first);
4606 for (const ValueInfo &VI : S->refs())
4607 DefOrUseGUIDs.insert(VI.getGUID());
4608
4609 auto ValueId = getValueId(I.first);
4610 assert(ValueId);
4611 SummaryToValueIdMap[S] = *ValueId;
4612
4613 // If this is invoked for an aliasee, we want to record the above
4614 // mapping, but then not emit a summary entry (if the aliasee is
4615 // to be imported, we will invoke this separately with IsAliasee=false).
4616 if (IsAliasee)
4617 return;
4618
4619 if (auto *AS = dyn_cast<AliasSummary>(S)) {
4620 // Will process aliases as a post-pass because the reader wants all
4621 // global to be loaded first.
4622 Aliases.push_back(AS);
4623 return;
4624 }
4625
4626 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
4627 NameVals.push_back(*ValueId);
4628 assert(ModuleIdMap.count(VS->modulePath()));
4629 NameVals.push_back(ModuleIdMap[VS->modulePath()]);
4630 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4631 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4632 for (auto &RI : VS->refs()) {
4633 auto RefValueId = getValueId(RI.getGUID());
4634 if (!RefValueId)
4635 continue;
4636 NameVals.push_back(*RefValueId);
4637 }
4638
4639 // Emit the finished record.
4641 FSModRefsAbbrev);
4642 NameVals.clear();
4643 MaybeEmitOriginalName(*S);
4644 return;
4645 }
4646
4647 auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> {
4648 if (!VI)
4649 return std::nullopt;
4650 return getValueId(VI.getGUID());
4651 };
4652
4653 auto *FS = cast<FunctionSummary>(S);
4654 writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
4655 getReferencedTypeIds(FS, ReferencedTypeIds);
4656
4658 Stream, FS, CallsiteAbbrev, AllocAbbrev,
4659 /*PerModule*/ false,
4660 /*GetValueId*/ [&](const ValueInfo &VI) -> unsigned {
4661 std::optional<unsigned> ValueID = GetValueId(VI);
4662 // This can happen in shared index files for distributed ThinLTO if
4663 // the callee function summary is not included. Record 0 which we
4664 // will have to deal with conservatively when doing any kind of
4665 // validation in the ThinLTO backends.
4666 if (!ValueID)
4667 return 0;
4668 return *ValueID;
4669 },
4670 /*GetStackIndex*/ [&](unsigned I) {
4671 // Get the corresponding index into the list of StackIds actually
4672 // being written for this combined index (which may be a subset in
4673 // the case of distributed indexes).
4674 assert(StackIdIndicesToIndex.contains(I));
4675 return StackIdIndicesToIndex[I];
4676 });
4677
4678 NameVals.push_back(*ValueId);
4679 assert(ModuleIdMap.count(FS->modulePath()));
4680 NameVals.push_back(ModuleIdMap[FS->modulePath()]);
4681 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4682 NameVals.push_back(FS->instCount());
4683 NameVals.push_back(getEncodedFFlags(FS->fflags()));
4684 NameVals.push_back(FS->entryCount());
4685
4686 // Fill in below
4687 NameVals.push_back(0); // numrefs
4688 NameVals.push_back(0); // rorefcnt
4689 NameVals.push_back(0); // worefcnt
4690
4691 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
4692 for (auto &RI : FS->refs()) {
4693 auto RefValueId = getValueId(RI.getGUID());
4694 if (!RefValueId)
4695 continue;
4696 NameVals.push_back(*RefValueId);
4697 if (RI.isReadOnly())
4698 RORefCnt++;
4699 else if (RI.isWriteOnly())
4700 WORefCnt++;
4701 Count++;
4702 }
4703 NameVals[6] = Count;
4704 NameVals[7] = RORefCnt;
4705 NameVals[8] = WORefCnt;
4706
4707 for (auto &EI : FS->calls()) {
4708 // If this GUID doesn't have a value id, it doesn't have a function
4709 // summary and we don't need to record any calls to it.
4710 std::optional<unsigned> CallValueId = GetValueId(EI.first);
4711 if (!CallValueId)
4712 continue;
4713 NameVals.push_back(*CallValueId);
4714 NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second));
4715 }
4716
4717 // Emit the finished record.
4718 Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals,
4719 FSCallsProfileAbbrev);
4720 NameVals.clear();
4721 MaybeEmitOriginalName(*S);
4722 });
4723
4724 for (auto *AS : Aliases) {
4725 auto AliasValueId = SummaryToValueIdMap[AS];
4726 assert(AliasValueId);
4727 NameVals.push_back(AliasValueId);
4728 assert(ModuleIdMap.count(AS->modulePath()));
4729 NameVals.push_back(ModuleIdMap[AS->modulePath()]);
4730 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4731 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
4732 assert(AliaseeValueId);
4733 NameVals.push_back(AliaseeValueId);
4734
4735 // Emit the finished record.
4736 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
4737 NameVals.clear();
4738 MaybeEmitOriginalName(*AS);
4739
4740 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
4741 getReferencedTypeIds(FS, ReferencedTypeIds);
4742 }
4743
4744 if (!Index.cfiFunctionDefs().empty()) {
4745 for (auto &S : Index.cfiFunctionDefs()) {
4746 if (DefOrUseGUIDs.count(
4748 NameVals.push_back(StrtabBuilder.add(S));
4749 NameVals.push_back(S.size());
4750 }
4751 }
4752 if (!NameVals.empty()) {
4753 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
4754 NameVals.clear();
4755 }
4756 }
4757
4758 if (!Index.cfiFunctionDecls().empty()) {
4759 for (auto &S : Index.cfiFunctionDecls()) {
4760 if (DefOrUseGUIDs.count(
4762 NameVals.push_back(StrtabBuilder.add(S));
4763 NameVals.push_back(S.size());
4764 }
4765 }
4766 if (!NameVals.empty()) {
4767 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
4768 NameVals.clear();
4769 }
4770 }
4771
4772 // Walk the GUIDs that were referenced, and write the
4773 // corresponding type id records.
4774 for (auto &T : ReferencedTypeIds) {
4775 auto TidIter = Index.typeIds().equal_range(T);
4776 for (auto It = TidIter.first; It != TidIter.second; ++It) {
4777 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
4778 It->second.second);
4779 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
4780 NameVals.clear();
4781 }
4782 }
4783
4784 if (Index.getBlockCount())
4786 ArrayRef<uint64_t>{Index.getBlockCount()});
4787
4788 Stream.ExitBlock();
4789}
4790
4791/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4792/// current llvm version, and a record for the epoch number.
4795
4796 // Write the "user readable" string identifying the bitcode producer
4797 auto Abbv = std::make_shared<BitCodeAbbrev>();
4801 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4803 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
4804
4805 // Write the epoch version
4806 Abbv = std::make_shared<BitCodeAbbrev>();
4809 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4810 constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
4811 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
4812 Stream.ExitBlock();
4813}
4814
4815void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
4816 // Emit the module's hash.
4817 // MODULE_CODE_HASH: [5*i32]
4818 if (GenerateHash) {
4819 uint32_t Vals[5];
4820 Hasher.update(ArrayRef<uint8_t>(
4821 reinterpret_cast<const uint8_t *>(View.data()), View.size()));
4822 std::array<uint8_t, 20> Hash = Hasher.result();
4823 for (int Pos = 0; Pos < 20; Pos += 4) {
4824 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
4825 }
4826
4827 // Emit the finished record.
4828 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
4829
4830 if (ModHash)
4831 // Save the written hash value.
4832 llvm::copy(Vals, std::begin(*ModHash));
4833 }
4834}
4835
4836void ModuleBitcodeWriter::write() {
4838
4840 // We will want to write the module hash at this point. Block any flushing so
4841 // we can have access to the whole underlying data later.
4842 Stream.markAndBlockFlushing();
4843
4844 writeModuleVersion();
4845
4846 // Emit blockinfo, which defines the standard abbreviations etc.
4847 writeBlockInfo();
4848
4849 // Emit information describing all of the types in the module.
4850 writeTypeTable();
4851
4852 // Emit information about attribute groups.
4853 writeAttributeGroupTable();
4854
4855 // Emit information about parameter attributes.
4856 writeAttributeTable();
4857
4858 writeComdats();
4859
4860 // Emit top-level description of module, including target triple, inline asm,
4861 // descriptors for global variables, and function prototype info.
4862 writeModuleInfo();
4863
4864 // Emit constants.
4865 writeModuleConstants();
4866
4867 // Emit metadata kind names.
4868 writeModuleMetadataKinds();
4869
4870 // Emit metadata.
4871 writeModuleMetadata();
4872
4873 // Emit module-level use-lists.
4875 writeUseListBlock(nullptr);
4876
4877 writeOperandBundleTags();
4878 writeSyncScopeNames();
4879
4880 // Emit function bodies.
4881 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
4882 for (const Function &F : M)
4883 if (!F.isDeclaration())
4884 writeFunction(F, FunctionToBitcodeIndex);
4885
4886 // Need to write after the above call to WriteFunction which populates
4887 // the summary information in the index.
4888 if (Index)
4889 writePerModuleGlobalValueSummary();
4890
4891 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
4892
4893 writeModuleHash(Stream.getMarkedBufferAndResumeFlushing());
4894
4895 Stream.ExitBlock();
4896}
4897
4899 uint32_t &Position) {
4900 support::endian::write32le(&Buffer[Position], Value);
4901 Position += 4;
4902}
4903
4904/// If generating a bc file on darwin, we have to emit a
4905/// header and trailer to make it compatible with the system archiver. To do
4906/// this we emit the following header, and then emit a trailer that pads the
4907/// file out to be a multiple of 16 bytes.
4908///
4909/// struct bc_header {
4910/// uint32_t Magic; // 0x0B17C0DE
4911/// uint32_t Version; // Version, currently always 0.
4912/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4913/// uint32_t BitcodeSize; // Size of traditional bitcode file.
4914/// uint32_t CPUType; // CPU specifier.
4915/// ... potentially more later ...
4916/// };
4918 const Triple &TT) {
4919 unsigned CPUType = ~0U;
4920
4921 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
4922 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4923 // number from /usr/include/mach/machine.h. It is ok to reproduce the
4924 // specific constants here because they are implicitly part of the Darwin ABI.
4925 enum {
4926 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
4927 DARWIN_CPU_TYPE_X86 = 7,
4928 DARWIN_CPU_TYPE_ARM = 12,
4929 DARWIN_CPU_TYPE_POWERPC = 18
4930 };
4931
4932 Triple::ArchType Arch = TT.getArch();
4933 if (Arch == Triple::x86_64)
4934 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
4935 else if (Arch == Triple::x86)
4936 CPUType = DARWIN_CPU_TYPE_X86;
4937 else if (Arch == Triple::ppc)
4938 CPUType = DARWIN_CPU_TYPE_POWERPC;
4939 else if (Arch == Triple::ppc64)
4940 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
4941 else if (Arch == Triple::arm || Arch == Triple::thumb)
4942 CPUType = DARWIN_CPU_TYPE_ARM;
4943
4944 // Traditional Bitcode starts after header.
4945 assert(Buffer.size() >= BWH_HeaderSize &&
4946 "Expected header size to be reserved");
4947 unsigned BCOffset = BWH_HeaderSize;
4948 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
4949
4950 // Write the magic and version.
4951 unsigned Position = 0;
4952 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4953 writeInt32ToBuffer(0, Buffer, Position); // Version.
4954 writeInt32ToBuffer(BCOffset, Buffer, Position);
4955 writeInt32ToBuffer(BCSize, Buffer, Position);
4956 writeInt32ToBuffer(CPUType, Buffer, Position);
4957
4958 // If the file is not a multiple of 16 bytes, insert dummy padding.
4959 while (Buffer.size() & 15)
4960 Buffer.push_back(0);
4961}
4962
4963/// Helper to write the header common to all bitcode files.
4965 // Emit the file header.
4966 Stream.Emit((unsigned)'B', 8);
4967 Stream.Emit((unsigned)'C', 8);
4968 Stream.Emit(0x0, 4);
4969 Stream.Emit(0xC, 4);
4970 Stream.Emit(0xE, 4);
4971 Stream.Emit(0xD, 4);
4972}
4973
4975 : Stream(new BitstreamWriter(Buffer)) {
4976 writeBitcodeHeader(*Stream);
4977}
4978
4980 : Stream(new BitstreamWriter(FS, FlushThreshold)) {
4981 writeBitcodeHeader(*Stream);
4982}
4983
4985
4986void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4987 Stream->EnterSubblock(Block, 3);
4988
4989 auto Abbv = std::make_shared<BitCodeAbbrev>();
4990 Abbv->Add(BitCodeAbbrevOp(Record));
4992 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4993
4994 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4995
4996 Stream->ExitBlock();
4997}
4998
5000 assert(!WroteStrtab && !WroteSymtab);
5001
5002 // If any module has module-level inline asm, we will require a registered asm
5003 // parser for the target so that we can create an accurate symbol table for
5004 // the module.
5005 for (Module *M : Mods) {
5006 if (M->getModuleInlineAsm().empty())
5007 continue;
5008
5009 std::string Err;
5010 const Triple TT(M->getTargetTriple());
5011 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
5012 if (!T || !T->hasMCAsmParser())
5013 return;
5014 }
5015
5016 WroteSymtab = true;
5017 SmallVector<char, 0> Symtab;
5018 // The irsymtab::build function may be unable to create a symbol table if the
5019 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
5020 // table is not required for correctness, but we still want to be able to
5021 // write malformed modules to bitcode files, so swallow the error.
5022 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
5023 consumeError(std::move(E));
5024 return;
5025 }
5026
5028 {Symtab.data(), Symtab.size()});
5029}
5030
5032 assert(!WroteStrtab);
5033
5034 std::vector<char> Strtab;
5035 StrtabBuilder.finalizeInOrder();
5036 Strtab.resize(StrtabBuilder.getSize());
5037 StrtabBuilder.write((uint8_t *)Strtab.data());
5038
5040 {Strtab.data(), Strtab.size()});
5041
5042 WroteStrtab = true;
5043}
5044
5046 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
5047 WroteStrtab = true;
5048}
5049
5051 bool ShouldPreserveUseListOrder,
5053 bool GenerateHash, ModuleHash *ModHash) {
5054 assert(!WroteStrtab);
5055
5056 // The Mods vector is used by irsymtab::build, which requires non-const
5057 // Modules in case it needs to materialize metadata. But the bitcode writer
5058 // requires that the module is materialized, so we can cast to non-const here,
5059 // after checking that it is in fact materialized.
5060 assert(M.isMaterialized());
5061 Mods.push_back(const_cast<Module *>(&M));
5062
5063 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5064 ShouldPreserveUseListOrder, Index,
5065 GenerateHash, ModHash);
5066 ModuleWriter.write();
5067}
5068
5071 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
5072 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
5073 ModuleToSummariesForIndex);
5074 IndexWriter.write();
5075}
5076
5077/// Write the specified module to the specified output stream.
5079 bool ShouldPreserveUseListOrder,
5081 bool GenerateHash, ModuleHash *ModHash) {
5082 auto Write = [&](BitcodeWriter &Writer) {
5083 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5084 ModHash);
5085 Writer.writeSymtab();
5086 Writer.writeStrtab();
5087 };
5088 Triple TT(M.getTargetTriple());
5089 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5090 // If this is darwin or another generic macho target, reserve space for the
5091 // header. Note that the header is computed *after* the output is known, so
5092 // we currently explicitly use a buffer, write to it, and then subsequently
5093 // flush to Out.
5094 SmallVector<char, 0> Buffer;
5095 Buffer.reserve(256 * 1024);
5096 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
5097 BitcodeWriter Writer(Buffer);
5098 Write(Writer);
5099 emitDarwinBCHeaderAndTrailer(Buffer, TT);
5100 Out.write(Buffer.data(), Buffer.size());
5101 } else {
5102 BitcodeWriter Writer(Out);
5103 Write(Writer);
5104 }
5105}
5106
5107void IndexBitcodeWriter::write() {
5109
5110 writeModuleVersion();
5111
5112 // Write the module paths in the combined index.
5113 writeModStrings();
5114
5115 // Write the summary combined index records.
5116 writeCombinedGlobalValueSummary();
5117
5118 Stream.ExitBlock();
5119}
5120
5121// Write the specified module summary index to the given raw output stream,
5122// where it will be written in a new bitcode block. This is used when
5123// writing the combined index file for ThinLTO. When writing a subset of the
5124// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
5127 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
5128 SmallVector<char, 0> Buffer;
5129 Buffer.reserve(256 * 1024);
5130
5131 BitcodeWriter Writer(Buffer);
5132 Writer.writeIndex(&Index, ModuleToSummariesForIndex);
5133 Writer.writeStrtab();
5134
5135 Out.write((char *)&Buffer.front(), Buffer.size());
5136}
5137
5138namespace {
5139
5140/// Class to manage the bitcode writing for a thin link bitcode file.
5141class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
5142 /// ModHash is for use in ThinLTO incremental build, generated while writing
5143 /// the module bitcode file.
5144 const ModuleHash *ModHash;
5145
5146public:
5147 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
5148 BitstreamWriter &Stream,
5150 const ModuleHash &ModHash)
5151 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5152 /*ShouldPreserveUseListOrder=*/false, &Index),
5153 ModHash(&ModHash) {}
5154
5155 void write();
5156
5157private:
5158 void writeSimplifiedModuleInfo();
5159};
5160
5161} // end anonymous namespace
5162
5163// This function writes a simpilified module info for thin link bitcode file.
5164// It only contains the source file name along with the name(the offset and
5165// size in strtab) and linkage for global values. For the global value info
5166// entry, in order to keep linkage at offset 5, there are three zeros used
5167// as padding.
5168void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5170 // Emit the module's source file name.
5171 {
5172 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
5174 if (Bits == SE_Char6)
5175 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
5176 else if (Bits == SE_Fixed7)
5177 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
5178
5179 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5180 auto Abbv = std::make_shared<BitCodeAbbrev>();
5183 Abbv->Add(AbbrevOpToUse);
5184 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5185
5186 for (const auto P : M.getSourceFileName())
5187 Vals.push_back((unsigned char)P);
5188
5189 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
5190 Vals.clear();
5191 }
5192
5193 // Emit the global variable information.
5194 for (const GlobalVariable &GV : M.globals()) {
5195 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
5196 Vals.push_back(StrtabBuilder.add(GV.getName()));
5197 Vals.push_back(GV.getName().size());
5198 Vals.push_back(0);
5199 Vals.push_back(0);
5200 Vals.push_back(0);
5201 Vals.push_back(getEncodedLinkage(GV));
5202
5204 Vals.clear();
5205 }
5206
5207 // Emit the function proto information.
5208 for (const Function &F : M) {
5209 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
5210 Vals.push_back(StrtabBuilder.add(F.getName()));
5211 Vals.push_back(F.getName().size());
5212 Vals.push_back(0);
5213 Vals.push_back(0);
5214 Vals.push_back(0);
5216
5218 Vals.clear();
5219 }
5220
5221 // Emit the alias information.
5222 for (const GlobalAlias &A : M.aliases()) {
5223 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
5224 Vals.push_back(StrtabBuilder.add(A.getName()));
5225 Vals.push_back(A.getName().size());
5226 Vals.push_back(0);
5227 Vals.push_back(0);
5228 Vals.push_back(0);
5230
5231 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
5232 Vals.clear();
5233 }
5234
5235 // Emit the ifunc information.
5236 for (const GlobalIFunc &I : M.ifuncs()) {
5237 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
5238 Vals.push_back(StrtabBuilder.add(I.getName()));
5239 Vals.push_back(I.getName().size());
5240 Vals.push_back(0);
5241 Vals.push_back(0);
5242 Vals.push_back(0);
5244
5245 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
5246 Vals.clear();
5247 }
5248}
5249
5250void ThinLinkBitcodeWriter::write() {
5252
5253 writeModuleVersion();
5254
5255 writeSimplifiedModuleInfo();
5256
5257 writePerModuleGlobalValueSummary();
5258
5259 // Write module hash.
5261
5262 Stream.ExitBlock();
5263}
5264
5267 const ModuleHash &ModHash) {
5268 assert(!WroteStrtab);
5269
5270 // The Mods vector is used by irsymtab::build, which requires non-const
5271 // Modules in case it needs to materialize metadata. But the bitcode writer
5272 // requires that the module is materialized, so we can cast to non-const here,
5273 // after checking that it is in fact materialized.
5274 assert(M.isMaterialized());
5275 Mods.push_back(const_cast<Module *>(&M));
5276
5277 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
5278 ModHash);
5279 ThinLinkWriter.write();
5280}
5281
5282// Write the specified thin link bitcode file to the given raw output stream,
5283// where it will be written in a new bitcode block. This is used when
5284// writing the per-module index file for ThinLTO.
5287 const ModuleHash &ModHash) {
5288 SmallVector<char, 0> Buffer;
5289 Buffer.reserve(256 * 1024);
5290
5291 BitcodeWriter Writer(Buffer);
5292 Writer.writeThinLinkBitcode(M, Index, ModHash);
5293 Writer.writeSymtab();
5294 Writer.writeStrtab();
5295
5296 Out.write((char *)&Buffer.front(), Buffer.size());
5297}
5298
5299static const char *getSectionNameForBitcode(const Triple &T) {
5300 switch (T.getObjectFormat()) {
5301 case Triple::MachO:
5302 return "__LLVM,__bitcode";
5303 case Triple::COFF:
5304 case Triple::ELF:
5305 case Triple::Wasm:
5307 return ".llvmbc";
5308 case Triple::GOFF:
5309 llvm_unreachable("GOFF is not yet implemented");
5310 break;
5311 case Triple::SPIRV:
5312 if (T.getVendor() == Triple::AMD)
5313 return ".llvmbc";
5314 llvm_unreachable("SPIRV is not yet implemented");
5315 break;
5316 case Triple::XCOFF:
5317 llvm_unreachable("XCOFF is not yet implemented");
5318 break;
5320 llvm_unreachable("DXContainer is not yet implemented");
5321 break;
5322 }
5323 llvm_unreachable("Unimplemented ObjectFormatType");
5324}
5325
5326static const char *getSectionNameForCommandline(const Triple &T) {
5327 switch (T.getObjectFormat()) {
5328 case Triple::MachO:
5329 return "__LLVM,__cmdline";
5330 case Triple::COFF:
5331 case Triple::ELF:
5332 case Triple::Wasm:
5334 return ".llvmcmd";
5335 case Triple::GOFF:
5336 llvm_unreachable("GOFF is not yet implemented");
5337 break;
5338 case Triple::SPIRV:
5339 if (T.getVendor() == Triple::AMD)
5340 return ".llvmcmd";
5341 llvm_unreachable("SPIRV is not yet implemented");
5342 break;
5343 case Triple::XCOFF:
5344 llvm_unreachable("XCOFF is not yet implemented");
5345 break;
5347 llvm_unreachable("DXC is not yet implemented");
5348 break;
5349 }
5350 llvm_unreachable("Unimplemented ObjectFormatType");
5351}
5352
5354 bool EmbedBitcode, bool EmbedCmdline,
5355 const std::vector<uint8_t> &CmdArgs) {
5356 // Save llvm.compiler.used and remove it.
5359 Type *UsedElementType = PointerType::getUnqual(M.getContext());
5360 GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
5361 for (auto *GV : UsedGlobals) {
5362 if (GV->getName() != "llvm.embedded.module" &&
5363 GV->getName() != "llvm.cmdline")
5364 UsedArray.push_back(
5366 }
5367 if (Used)
5368 Used->eraseFromParent();
5369
5370 // Embed the bitcode for the llvm module.
5371 std::string Data;
5372 ArrayRef<uint8_t> ModuleData;
5373 Triple T(M.getTargetTriple());
5374
5375 if (EmbedBitcode) {
5376 if (Buf.getBufferSize() == 0 ||
5377 !isBitcode((const unsigned char *)Buf.getBufferStart(),
5378 (const unsigned char *)Buf.getBufferEnd())) {
5379 // If the input is LLVM Assembly, bitcode is produced by serializing
5380 // the module. Use-lists order need to be preserved in this case.
5382 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
5383 ModuleData =
5384 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
5385 } else
5386 // If the input is LLVM bitcode, write the input byte stream directly.
5387 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
5388 Buf.getBufferSize());
5389 }
5390 llvm::Constant *ModuleConstant =
5391 llvm::ConstantDataArray::get(M.getContext(), ModuleData);
5393 M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
5394 ModuleConstant);
5396 // Set alignment to 1 to prevent padding between two contributions from input
5397 // sections after linking.
5398 GV->setAlignment(Align(1));
5399 UsedArray.push_back(
5401 if (llvm::GlobalVariable *Old =
5402 M.getGlobalVariable("llvm.embedded.module", true)) {
5403 assert(Old->hasZeroLiveUses() &&
5404 "llvm.embedded.module can only be used once in llvm.compiler.used");
5405 GV->takeName(Old);
5406 Old->eraseFromParent();
5407 } else {
5408 GV->setName("llvm.embedded.module");
5409 }
5410
5411 // Skip if only bitcode needs to be embedded.
5412 if (EmbedCmdline) {
5413 // Embed command-line options.
5414 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
5415 CmdArgs.size());
5416 llvm::Constant *CmdConstant =
5417 llvm::ConstantDataArray::get(M.getContext(), CmdData);
5418 GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
5420 CmdConstant);
5422 GV->setAlignment(Align(1));
5423 UsedArray.push_back(
5425 if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
5426 assert(Old->hasZeroLiveUses() &&
5427 "llvm.cmdline can only be used once in llvm.compiler.used");
5428 GV->takeName(Old);
5429 Old->eraseFromParent();
5430 } else {
5431 GV->setName("llvm.cmdline");
5432 }
5433 }
5434
5435 if (UsedArray.empty())
5436 return;
5437
5438 // Recreate llvm.compiler.used.
5439 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
5440 auto *NewUsed = new GlobalVariable(
5442 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
5443 NewUsed->setSection("llvm.metadata");
5444}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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...
static void writeDIMacro(raw_ostream &Out, const DIMacro *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2352
static void writeDIGlobalVariableExpression(raw_ostream &Out, const DIGlobalVariableExpression *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2499
static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2190
static void writeDIStringType(raw_ostream &Out, const DIStringType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2139
static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2413
static void writeDIModule(raw_ostream &Out, const DIModule *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2373
static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &)
Definition: AsmWriter.cpp:2234
static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2223
static void writeDILabel(raw_ostream &Out, const DILabel *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2448
static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2157
static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2523
static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2509
static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2279
static void writeDILocation(raw_ostream &Out, const DILocation *DL, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2000
static void writeDINamespace(raw_ostream &Out, const DINamespace *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2330
static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2340
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, AsmWriterContext &)
Definition: AsmWriter.cpp:2124
static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:1982
static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2432
static void writeDITemplateTypeParameter(raw_ostream &Out, const DITemplateTypeParameter *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2388
static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2249
static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2061
static void writeDISubrange(raw_ostream &Out, const DISubrange *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2020
static void writeDILexicalBlockFile(raw_ostream &Out, const DILexicalBlockFile *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2318
static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, AsmWriterContext &)
Definition: AsmWriter.cpp:2112
static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:1761
static void writeDIExpression(raw_ostream &Out, const DIExpression *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2459
static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2014
static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2307
static void writeDIArgList(raw_ostream &Out, const DIArgList *N, AsmWriterContext &WriterCtx, bool FromValue=false)
Definition: AsmWriter.cpp:2484
static void writeDITemplateValueParameter(raw_ostream &Out, const DITemplateValueParameter *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2399
static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2363
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static unsigned serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta)
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 unsigned getEncodedUnaryOpcode(unsigned Opcode)
static void emitSignedInt64(SmallVectorImpl< uint64_t > &Vals, uint64_t V)
static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags)
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 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 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 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 writeTypeIdCompatibleVtableSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, const std::string &Id, const TypeIdCompatibleVtableInfo &Summary, ValueEnumerator &VE)
static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl< char > &Buffer, uint32_t &Position)
MetadataAbbrev
@ LastPlusOne
static const char * getSectionNameForBitcode(const Triple &T)
static void writeFunctionHeapProfileRecords(BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev, unsigned AllocAbbrev, bool PerModule, std::function< unsigned(const ValueInfo &VI)> GetValueID, std::function< unsigned(unsigned)> GetStackIndex)
static void writeTypeIdSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, const std::string &Id, const TypeIdSummary &Summary)
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
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:530
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...
Module.h This file contains the declarations for the Module class.
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:77
unsigned getNumWords() const
Get the number of words.
Definition: APInt.h:1454
unsigned getActiveWords() const
Compute the number of active words in the value of this APInt.
Definition: APInt.h:1477
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition: APInt.h:548
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1521
Alias summary information.
const GlobalValueSummary & getAliasee() const
an instruction to allocate memory on the stack
Definition: Instructions.h:60
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Definition: Instructions.h:146
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:121
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:114
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
Definition: Instructions.h:136
unsigned getAddressSpace() const
Return the address space for the allocation.
Definition: Instructions.h:101
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:165
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
Class to represent array types.
Definition: DerivedTypes.h:371
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:647
BinOp
This enumeration lists the possible modifications atomicrmw can make.
Definition: Instructions.h:707
@ Add
*p = old + v
Definition: Instructions.h:711
@ FAdd
*p = old + v
Definition: Instructions.h:732
@ Min
*p = old <signed v ? old : v
Definition: Instructions.h:725
@ Or
*p = old | v
Definition: Instructions.h:719
@ Sub
*p = old - v
Definition: Instructions.h:713
@ And
*p = old & v
Definition: Instructions.h:715
@ Xor
*p = old ^ v
Definition: Instructions.h:721
@ FSub
*p = old - v
Definition: Instructions.h:735
@ UIncWrap
Increment one up to a maximum value.
Definition: Instructions.h:747
@ Max
*p = old >signed v ? old : v
Definition: Instructions.h:723
@ UMin
*p = old <unsigned v ? old : v
Definition: Instructions.h:729
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
Definition: Instructions.h:743
@ UMax
*p = old >unsigned v ? old : v
Definition: Instructions.h:727
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
Definition: Instructions.h:739
@ UDecWrap
Decrement one until a minimum value or zero.
Definition: Instructions.h:751
@ Nand
*p = ~(old & v)
Definition: Instructions.h:717
bool hasAttributes() const
Return true if attributes exists in this set.
Definition: Attributes.h:390
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 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 writeIndex(const ModuleSummaryIndex *Index, const std::map< std::string, GVSummaryMapTy > *ModuleToSummariesForIndex)
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:890
static BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Definition: Constants.cpp:1851
Conditional or Unconditional Branch instruction.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1236
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
Definition: InstrTypes.h:2112
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
Definition: InstrTypes.h:2056
CallingConv::ID getCallingConv() const
Definition: InstrTypes.h:1523
Value * getCalledOperand() const
Definition: InstrTypes.h:1458
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1410
FunctionType * getFunctionType() const
Definition: InstrTypes.h:1323
unsigned arg_size() const
Definition: InstrTypes.h:1408
AttributeList getAttributes() const
Return the parameter attributes for this call.
Definition: InstrTypes.h:1542
bool hasOperandBundles() const
Return true if this User has any operand bundles.
Definition: InstrTypes.h:2061
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:1292
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:706
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:584
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:1084
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:2192
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:269
This is the shared class of boolean and integer constants.
Definition: Constants.h:81
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:41
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:151
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:145
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:220
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:1477
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:137
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:267
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:282
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:1067
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:889
Tuple of metadata.
Definition: Metadata.h:1470
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:1729
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:662
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:479
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:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void assign(size_type NumElts, ValueParamT Elt)
Definition: SmallVector.h:717
void reserve(size_type N)
Definition: SmallVector.h:676
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:696
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:818
void resize(size_type N)
Definition: SmallVector.h:651
void push_back(const T &Elt)
Definition: SmallVector.h:426
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:299
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
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:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
iterator begin() const
Definition: StringRef.h:111
iterator end() const
Definition: StringRef.h:113
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:216
Multiway switch.
Class to represent target extensions types, which are generally unintrospectable from target-independ...
Definition: DerivedTypes.h:720
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
@ DXContainer
Definition: Triple.h:301
@ UnknownObjectFormat
Definition: Triple.h:298
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:160
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:154
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition: Type.h:146
@ X86_MMXTyID
MMX vectors (64 bits, X86 specific)
Definition: Type.h:66
@ X86_AMXTyID
AMX vectors (8192 bits, X86 specific)
Definition: Type.h:67
@ FunctionTyID
Functions.
Definition: Type.h:72
@ ArrayTyID
Arrays.
Definition: Type.h:75
@ TypedPointerTyID
Typed pointer used by some GPU targets.
Definition: Type.h:78
@ HalfTyID
16-bit floating point type
Definition: Type.h:56
@ TargetExtTyID
Target extension type.
Definition: Type.h:79
@ VoidTyID
type with no size
Definition: Type.h:63
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition: Type.h:77
@ LabelTyID
Labels.
Definition: Type.h:64
@ FloatTyID
32-bit floating point type
Definition: Type.h:58
@ StructTyID
Structures.
Definition: Type.h:74
@ IntegerTyID
Arbitrary bit width integers.
Definition: Type.h:71
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition: Type.h:76
@ 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:68
@ PointerTyID
Pointers.
Definition: Type.h:73
@ 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:166
bool isFP128Ty() const
Return true if this is 'fp128'.
Definition: Type.h:163
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition: Type.h:143
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition: Type.h:157
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:348
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:1074
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
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:811
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
const uint64_t Version
Definition: InstrProf.h:1108
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:206
@ 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:348
@ METADATA_COMMON_BLOCK
Definition: LLVMBitCodes.h:368
@ METADATA_STRING_TYPE
Definition: LLVMBitCodes.h:365
@ METADATA_MACRO_FILE
Definition: LLVMBitCodes.h:358
@ METADATA_TEMPLATE_VALUE
Definition: LLVMBitCodes.h:350
@ METADATA_LEXICAL_BLOCK_FILE
Definition: LLVMBitCodes.h:347
@ METADATA_INDEX_OFFSET
Definition: LLVMBitCodes.h:362
@ METADATA_LEXICAL_BLOCK
Definition: LLVMBitCodes.h:346
@ METADATA_SUBPROGRAM
Definition: LLVMBitCodes.h:345
@ METADATA_SUBROUTINE_TYPE
Definition: LLVMBitCodes.h:343
@ METADATA_GLOBAL_DECL_ATTACHMENT
Definition: LLVMBitCodes.h:360
@ METADATA_LOCAL_VAR
Definition: LLVMBitCodes.h:352
@ METADATA_GLOBAL_VAR
Definition: LLVMBitCodes.h:351
@ METADATA_EXPRESSION
Definition: LLVMBitCodes.h:353
@ METADATA_ATTACHMENT
Definition: LLVMBitCodes.h:335
@ METADATA_OBJC_PROPERTY
Definition: LLVMBitCodes.h:354
@ METADATA_NAMED_NODE
Definition: LLVMBitCodes.h:334
@ METADATA_IMPORTED_ENTITY
Definition: LLVMBitCodes.h:355
@ METADATA_GENERIC_SUBRANGE
Definition: LLVMBitCodes.h:369
@ METADATA_ASSIGN_ID
Definition: LLVMBitCodes.h:371
@ METADATA_COMPILE_UNIT
Definition: LLVMBitCodes.h:344
@ METADATA_COMPOSITE_TYPE
Definition: LLVMBitCodes.h:342
@ METADATA_ENUMERATOR
Definition: LLVMBitCodes.h:338
@ METADATA_DERIVED_TYPE
Definition: LLVMBitCodes.h:341
@ METADATA_TEMPLATE_TYPE
Definition: LLVMBitCodes.h:349
@ METADATA_GLOBAL_VAR_EXPR
Definition: LLVMBitCodes.h:361
@ METADATA_BASIC_TYPE
Definition: LLVMBitCodes.h:339
@ METADATA_DISTINCT_NODE
Definition: LLVMBitCodes.h:329
@ METADATA_GENERIC_DEBUG
Definition: LLVMBitCodes.h:336
@ 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_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:315
@ FS_COMBINED_ALLOC_INFO
Definition: LLVMBitCodes.h:320
@ FS_PERMODULE_PROFILE
Definition: LLVMBitCodes.h:214
@ FS_PERMODULE_CALLSITE_INFO
Definition: LLVMBitCodes.h:308
@ FS_PERMODULE_ALLOC_INFO
Definition: LLVMBitCodes.h:311
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
Definition: LLVMBitCodes.h:255
@ BITCODE_CURRENT_EPOCH
Definition: LLVMBitCodes.h:81
@ IDENTIFICATION_CODE_EPOCH
Definition: LLVMBitCodes.h:72
@ IDENTIFICATION_CODE_STRING
Definition: LLVMBitCodes.h:71
@ CST_CODE_BLOCKADDRESS
Definition: LLVMBitCodes.h:398
@ CST_CODE_NO_CFI_VALUE
Definition: LLVMBitCodes.h:409
@ CST_CODE_CE_SHUFVEC_EX
Definition: LLVMBitCodes.h:396
@ CST_CODE_CE_EXTRACTELT
Definition: LLVMBitCodes.h:390
@ CST_CODE_CE_SHUFFLEVEC
Definition: LLVMBitCodes.h:392
@ CST_CODE_WIDE_INTEGER
Definition: LLVMBitCodes.h:381
@ CST_CODE_DSO_LOCAL_EQUIVALENT
Definition: LLVMBitCodes.h:405
@ CST_CODE_AGGREGATE
Definition: LLVMBitCodes.h:383
@ CST_CODE_CE_INSERTELT
Definition: LLVMBitCodes.h:391
@ CST_CODE_CE_GEP_WITH_INRANGE
Definition: LLVMBitCodes.h:414
@ CST_CODE_INLINEASM
Definition: LLVMBitCodes.h:410
@ CALL_EXPLICIT_TYPE
Definition: LLVMBitCodes.h:553
@ COMDAT_SELECTION_KIND_LARGEST
Definition: LLVMBitCodes.h:764
@ COMDAT_SELECTION_KIND_ANY
Definition: LLVMBitCodes.h:762
@ COMDAT_SELECTION_KIND_SAME_SIZE
Definition: LLVMBitCodes.h:766
@ COMDAT_SELECTION_KIND_EXACT_MATCH
Definition: LLVMBitCodes.h:763
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
Definition: LLVMBitCodes.h:765
@ ATTR_KIND_STACK_PROTECT
Definition: LLVMBitCodes.h:690
@ ATTR_KIND_NO_UNWIND
Definition: LLVMBitCodes.h:682
@ ATTR_KIND_STACK_PROTECT_STRONG
Definition: LLVMBitCodes.h:692
@ ATTR_KIND_SANITIZE_MEMORY
Definition: LLVMBitCodes.h:696
@ ATTR_KIND_SAFESTACK
Definition: LLVMBitCodes.h:708
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
Definition: LLVMBitCodes.h:683
@ ATTR_KIND_SWIFT_ERROR
Definition: LLVMBitCodes.h:711
@ ATTR_KIND_STRUCT_RET
Definition: LLVMBitCodes.h:693
@ ATTR_KIND_MIN_SIZE
Definition: LLVMBitCodes.h:670
@ ATTR_KIND_NO_CALLBACK
Definition: LLVMBitCodes.h:735
@ ATTR_KIND_NO_CAPTURE
Definition: LLVMBitCodes.h:675
@ ATTR_KIND_FNRETTHUNK_EXTERN
Definition: LLVMBitCodes.h:748
@ ATTR_KIND_SANITIZE_ADDRESS
Definition: LLVMBitCodes.h:694
@ ATTR_KIND_NO_IMPLICIT_FLOAT
Definition: LLVMBitCodes.h:677
@ ATTR_KIND_NO_BUILTIN
Definition: LLVMBitCodes.h:674
@ ATTR_KIND_NO_RECURSE
Definition: LLVMBitCodes.h:712
@ ATTR_KIND_DEAD_ON_UNWIND
Definition: LLVMBitCodes.h:755
@ ATTR_KIND_CONVERGENT
Definition: LLVMBitCodes.h:707
@ ATTR_KIND_RETURNED
Definition: LLVMBitCodes.h:686
@ ATTR_KIND_STACK_ALIGNMENT
Definition: LLVMBitCodes.h:689
@ ATTR_KIND_SWIFT_SELF
Definition: LLVMBitCodes.h:710
@ ATTR_KIND_ALLOC_SIZE
Definition: LLVMBitCodes.h:715
@ ATTR_KIND_STACK_PROTECT_REQ
Definition: LLVMBitCodes.h:691
@ ATTR_KIND_INLINE_HINT
Definition: LLVMBitCodes.h:668
@ ATTR_KIND_NON_NULL
Definition: LLVMBitCodes.h:703
@ ATTR_KIND_NULL_POINTER_IS_VALID
Definition: LLVMBitCodes.h:731
@ ATTR_KIND_SANITIZE_HWADDRESS
Definition: LLVMBitCodes.h:719
@ ATTR_KIND_NO_RETURN
Definition: LLVMBitCodes.h:681
@ ATTR_KIND_MUSTPROGRESS
Definition: LLVMBitCodes.h:734
@ ATTR_KIND_RETURNS_TWICE
Definition: LLVMBitCodes.h:687
@ ATTR_KIND_SHADOWCALLSTACK
Definition: LLVMBitCodes.h:722
@ ATTR_KIND_OPT_FOR_FUZZING
Definition: LLVMBitCodes.h:721
@ ATTR_KIND_WRITABLE
Definition: LLVMBitCodes.h:753
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
Definition: LLVMBitCodes.h:757
@ ATTR_KIND_INITIALIZES
Definition: LLVMBitCodes.h:758
@ ATTR_KIND_ALLOCATED_POINTER
Definition: LLVMBitCodes.h:745
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
Definition: LLVMBitCodes.h:742
@ ATTR_KIND_SKIP_PROFILE
Definition: LLVMBitCodes.h:749
@ ATTR_KIND_ELEMENTTYPE
Definition: LLVMBitCodes.h:741
@ ATTR_KIND_ALLOC_KIND
Definition: LLVMBitCodes.h:746
@ ATTR_KIND_NO_MERGE
Definition: LLVMBitCodes.h:730
@ ATTR_KIND_STRICT_FP
Definition: LLVMBitCodes.h:718
@ ATTR_KIND_NO_DUPLICATE
Definition: LLVMBitCodes.h:676
@ ATTR_KIND_ALLOC_ALIGN
Definition: LLVMBitCodes.h:744
@ ATTR_KIND_NON_LAZY_BIND
Definition: LLVMBitCodes.h:679
@ ATTR_KIND_DEREFERENCEABLE
Definition: LLVMBitCodes.h:705
@ ATTR_KIND_READ_NONE
Definition: LLVMBitCodes.h:684
@ ATTR_KIND_UW_TABLE
Definition: LLVMBitCodes.h:697
@ ATTR_KIND_OPTIMIZE_NONE
Definition: LLVMBitCodes.h:701
@ ATTR_KIND_WRITEONLY
Definition: LLVMBitCodes.h:716
@ ATTR_KIND_NO_RED_ZONE
Definition: LLVMBitCodes.h:680
@ ATTR_KIND_NOCF_CHECK
Definition: LLVMBitCodes.h:720
@ ATTR_KIND_NO_PROFILE
Definition: LLVMBitCodes.h:737
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
Definition: LLVMBitCodes.h:706
@ ATTR_KIND_IN_ALLOCA
Definition: LLVMBitCodes.h:702
@ ATTR_KIND_READ_ONLY
Definition: LLVMBitCodes.h:685
@ ATTR_KIND_ALIGNMENT
Definition: LLVMBitCodes.h:665
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
Definition: LLVMBitCodes.h:723
@ ATTR_KIND_ALWAYS_INLINE
Definition: LLVMBitCodes.h:666
@ ATTR_KIND_NOFPCLASS
Definition: LLVMBitCodes.h:751
@ ATTR_KIND_WILLRETURN
Definition: LLVMBitCodes.h:725
@ ATTR_KIND_PRESPLIT_COROUTINE
Definition: LLVMBitCodes.h:747
@ ATTR_KIND_NO_ALIAS
Definition: LLVMBitCodes.h:673
@ ATTR_KIND_VSCALE_RANGE
Definition: LLVMBitCodes.h:738
@ ATTR_KIND_NO_SANITIZE_COVERAGE
Definition: LLVMBitCodes.h:740
@ ATTR_KIND_JUMP_TABLE
Definition: LLVMBitCodes.h:704
@ ATTR_KIND_SPECULATABLE
Definition: LLVMBitCodes.h:717
@ ATTR_KIND_NO_INLINE
Definition: LLVMBitCodes.h:678
@ ATTR_KIND_NO_SANITIZE_BOUNDS
Definition: LLVMBitCodes.h:743
@ ATTR_KIND_SANITIZE_MEMTAG
Definition: LLVMBitCodes.h:728
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
Definition: LLVMBitCodes.h:754
@ ATTR_KIND_SANITIZE_THREAD
Definition: LLVMBitCodes.h:695
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
Definition: LLVMBitCodes.h:752
@ ATTR_KIND_PREALLOCATED
Definition: LLVMBitCodes.h:729
@ ATTR_KIND_SWIFT_ASYNC
Definition: LLVMBitCodes.h:739
@ OBO_NO_SIGNED_WRAP
Definition: LLVMBitCodes.h:494
@ OBO_NO_UNSIGNED_WRAP
Definition: LLVMBitCodes.h:493
@ TIO_NO_UNSIGNED_WRAP
Definition: LLVMBitCodes.h:500
@ TIO_NO_SIGNED_WRAP
Definition: LLVMBitCodes.h:501
@ USELIST_CODE_DEFAULT
Definition: LLVMBitCodes.h:659
@ 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:436
@ 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:629
@ FUNC_CODE_INST_LANDINGPAD
Definition: LLVMBitCodes.h:627
@ FUNC_CODE_INST_EXTRACTVAL
Definition: LLVMBitCodes.h:592
@ FUNC_CODE_INST_CATCHPAD
Definition: LLVMBitCodes.h:630
@ FUNC_CODE_INST_RESUME
Definition: LLVMBitCodes.h:614
@ FUNC_CODE_INST_CMP2
Definition: LLVMBitCodes.h:596
@ FUNC_CODE_INST_FENCE
Definition: LLVMBitCodes.h:607
@ FUNC_CODE_INST_CALLBR
Definition: LLVMBitCodes.h:638
@ FUNC_CODE_INST_CATCHSWITCH
Definition: LLVMBitCodes.h:632
@ FUNC_CODE_INST_VSELECT
Definition: LLVMBitCodes.h:598
@ FUNC_CODE_INST_GEP
Definition: LLVMBitCodes.h:621
@ FUNC_CODE_INST_CLEANUPRET
Definition: LLVMBitCodes.h:628
@ FUNC_CODE_DEBUG_RECORD_VALUE
Definition: LLVMBitCodes.h:646
@ FUNC_CODE_INST_LOADATOMIC
Definition: LLVMBitCodes.h:617
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
Definition: LLVMBitCodes.h:650
@ FUNC_CODE_INST_LOAD
Definition: LLVMBitCodes.h:583
@ FUNC_CODE_INST_STOREATOMIC
Definition: LLVMBitCodes.h:623
@ FUNC_CODE_INST_ATOMICRMW
Definition: LLVMBitCodes.h:641
@ FUNC_CODE_INST_BINOP
Definition: LLVMBitCodes.h:563
@ FUNC_CODE_INST_STORE
Definition: LLVMBitCodes.h:622
@ FUNC_CODE_DEBUG_LOC_AGAIN
Definition: LLVMBitCodes.h:602
@ FUNC_CODE_INST_EXTRACTELT
Definition: LLVMBitCodes.h:567
@ FUNC_CODE_INST_INDIRECTBR
Definition: LLVMBitCodes.h:600
@ FUNC_CODE_INST_INVOKE
Definition: LLVMBitCodes.h:575
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
Definition: LLVMBitCodes.h:653
@ FUNC_CODE_INST_INSERTVAL
Definition: LLVMBitCodes.h:593
@ FUNC_CODE_DECLAREBLOCKS
Definition: LLVMBitCodes.h:561
@ FUNC_CODE_DEBUG_RECORD_LABEL
Definition: LLVMBitCodes.h:655
@ FUNC_CODE_INST_SWITCH
Definition: LLVMBitCodes.h:574
@ FUNC_CODE_INST_PHI
Definition: LLVMBitCodes.h:579
@ FUNC_CODE_INST_RET
Definition: LLVMBitCodes.h:572
@ FUNC_CODE_INST_CALL
Definition: LLVMBitCodes.h:604
@ FUNC_CODE_INST_ALLOCA
Definition: LLVMBitCodes.h:582
@ FUNC_CODE_INST_INSERTELT
Definition: LLVMBitCodes.h:568
@ FUNC_CODE_BLOCKADDR_USERS
Definition: LLVMBitCodes.h:644
@ FUNC_CODE_INST_CLEANUPPAD
Definition: LLVMBitCodes.h:631
@ FUNC_CODE_INST_SHUFFLEVEC
Definition: LLVMBitCodes.h:569
@ FUNC_CODE_INST_UNOP
Definition: LLVMBitCodes.h:637
@ FUNC_CODE_INST_VAARG
Definition: LLVMBitCodes.h:586
@ FUNC_CODE_INST_FREEZE
Definition: LLVMBitCodes.h:640
@ FUNC_CODE_INST_CMPXCHG
Definition: LLVMBitCodes.h:624
@ FUNC_CODE_INST_UNREACHABLE
Definition: LLVMBitCodes.h:577
@ FUNC_CODE_INST_CAST
Definition: LLVMBitCodes.h:564
@ FUNC_CODE_DEBUG_LOC
Definition: LLVMBitCodes.h:606
@ FUNC_CODE_DEBUG_RECORD_DECLARE
Definition: LLVMBitCodes.h:648
@ FUNC_CODE_OPERAND_BUNDLE
Definition: LLVMBitCodes.h:636
@ 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:539
@ ORDERING_UNORDERED
Definition: LLVMBitCodes.h:540
@ ORDERING_MONOTONIC
Definition: LLVMBitCodes.h:541
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:372
constexpr double e
Definition: MathExtras.h:31
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:337
unsigned encode(MaybeAlign A)
Returns a representation of the alignment that encodes undefined as 0.
Definition: Alignment.h:217
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 are tuples (A,...
Definition: STLExtras.h:2400
void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const std::map< std::string, GVSummaryMapTy > *ModuleToSummariesForIndex=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
AddressSpace
Definition: NVPTXBaseInfo.h:21
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...
@ 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:2067
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:1729
Error write(MCStreamer &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue)
Definition: DWP.cpp:625
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
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.
DWARFExpression::Operation Op
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1824
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:191
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:854
#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,...