LLVM 23.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"
33#include "llvm/Config/llvm-config.h"
34#include "llvm/IR/Attributes.h"
35#include "llvm/IR/BasicBlock.h"
36#include "llvm/IR/Comdat.h"
37#include "llvm/IR/Constant.h"
39#include "llvm/IR/Constants.h"
41#include "llvm/IR/DebugLoc.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/GlobalAlias.h"
45#include "llvm/IR/GlobalIFunc.h"
47#include "llvm/IR/GlobalValue.h"
49#include "llvm/IR/InlineAsm.h"
50#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
53#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/Metadata.h"
55#include "llvm/IR/Module.h"
57#include "llvm/IR/Operator.h"
58#include "llvm/IR/Type.h"
60#include "llvm/IR/Value.h"
71#include "llvm/Support/Endian.h"
72#include "llvm/Support/Error.h"
75#include "llvm/Support/SHA1.h"
78#include <algorithm>
79#include <cassert>
80#include <cstddef>
81#include <cstdint>
82#include <iterator>
83#include <map>
84#include <memory>
85#include <optional>
86#include <string>
87#include <utility>
88#include <vector>
89
90using namespace llvm;
91using namespace llvm::memprof;
92
94 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
95 cl::desc("Number of metadatas above which we emit an index "
96 "to enable lazy-loading"));
98 "bitcode-flush-threshold", cl::Hidden, cl::init(512),
99 cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
100
101// Since we only use the context information in the memprof summary records in
102// the LTO backends to do assertion checking, save time and space by only
103// serializing the context for non-NDEBUG builds.
104// TODO: Currently this controls writing context of the allocation info records,
105// which are larger and more expensive, but we should do this for the callsite
106// records as well.
107// FIXME: Convert to a const once this has undergone more sigificant testing.
108static cl::opt<bool>
109 CombinedIndexMemProfContext("combined-index-memprof-context", cl::Hidden,
110#ifdef NDEBUG
111 cl::init(false),
112#else
113 cl::init(true),
114#endif
115 cl::desc(""));
116
118 "preserve-bc-uselistorder", cl::Hidden, cl::init(true),
119 cl::desc("Preserve use-list order when writing LLVM bitcode."));
120
121namespace llvm {
123}
124
125namespace {
126
127/// These are manifest constants used by the bitcode writer. They do not need to
128/// be kept in sync with the reader, but need to be consistent within this file.
129enum {
130 // VALUE_SYMTAB_BLOCK abbrev id's.
131 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
132 VST_ENTRY_7_ABBREV,
133 VST_ENTRY_6_ABBREV,
134 VST_BBENTRY_6_ABBREV,
135
136 // CONSTANTS_BLOCK abbrev id's.
137 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
138 CONSTANTS_INTEGER_ABBREV,
139 CONSTANTS_BYTE_ABBREV,
140 CONSTANTS_CE_CAST_Abbrev,
141 CONSTANTS_NULL_Abbrev,
142
143 // FUNCTION_BLOCK abbrev id's.
144 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
145 FUNCTION_INST_STORE_ABBREV,
146 FUNCTION_INST_UNOP_ABBREV,
147 FUNCTION_INST_UNOP_FLAGS_ABBREV,
148 FUNCTION_INST_BINOP_ABBREV,
149 FUNCTION_INST_BINOP_FLAGS_ABBREV,
150 FUNCTION_INST_CAST_ABBREV,
151 FUNCTION_INST_CAST_FLAGS_ABBREV,
152 FUNCTION_INST_RET_VOID_ABBREV,
153 FUNCTION_INST_RET_VAL_ABBREV,
154 FUNCTION_INST_BR_UNCOND_ABBREV,
155 FUNCTION_INST_BR_COND_ABBREV,
156 FUNCTION_INST_UNREACHABLE_ABBREV,
157 FUNCTION_INST_GEP_ABBREV,
158 FUNCTION_INST_CMP_ABBREV,
159 FUNCTION_INST_CMP_FLAGS_ABBREV,
160 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
161 FUNCTION_DEBUG_LOC_ABBREV,
162};
163
164/// Abstract class to manage the bitcode writing, subclassed for each bitcode
165/// file type.
166class BitcodeWriterBase {
167protected:
168 /// The stream created and owned by the client.
169 BitstreamWriter &Stream;
170
171 StringTableBuilder &StrtabBuilder;
172
173public:
174 /// Constructs a BitcodeWriterBase object that writes to the provided
175 /// \p Stream.
176 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
177 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
178
179protected:
180 void writeModuleVersion();
181};
182
183void BitcodeWriterBase::writeModuleVersion() {
184 // VERSION: [version#]
185 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
186}
187
188/// Base class to manage the module bitcode writing, currently subclassed for
189/// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
190class ModuleBitcodeWriterBase : public BitcodeWriterBase {
191protected:
192 /// The Module to write to bitcode.
193 const Module &M;
194
195 /// Enumerates ids for all values in the module.
196 ValueEnumerator VE;
197
198 /// Optional per-module index to write for ThinLTO.
199 const ModuleSummaryIndex *Index;
200
201 /// Map that holds the correspondence between GUIDs in the summary index,
202 /// that came from indirect call profiles, and a value id generated by this
203 /// class to use in the VST and summary block records.
204 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
205
206 /// Tracks the last value id recorded in the GUIDToValueMap.
207 unsigned GlobalValueId;
208
209 /// Saves the offset of the VSTOffset record that must eventually be
210 /// backpatched with the offset of the actual VST.
211 uint64_t VSTOffsetPlaceholder = 0;
212
213public:
214 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
215 /// writing to the provided \p Buffer.
216 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
217 BitstreamWriter &Stream,
218 bool ShouldPreserveUseListOrder,
219 const ModuleSummaryIndex *Index)
220 : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
221 VE(M, PreserveBitcodeUseListOrder.getNumOccurrences()
223 : ShouldPreserveUseListOrder),
224 Index(Index) {
225 // Assign ValueIds to any callee values in the index that came from
226 // indirect call profiles and were recorded as a GUID not a Value*
227 // (which would have been assigned an ID by the ValueEnumerator).
228 // The starting ValueId is just after the number of values in the
229 // ValueEnumerator, so that they can be emitted in the VST.
230 GlobalValueId = VE.getValues().size();
231 if (!Index)
232 return;
233 for (const auto &GUIDSummaryLists : *Index)
234 // Examine all summaries for this GUID.
235 for (auto &Summary : GUIDSummaryLists.second.getSummaryList())
236 if (auto FS = dyn_cast<FunctionSummary>(Summary.get())) {
237 // For each call in the function summary, see if the call
238 // is to a GUID (which means it is for an indirect call,
239 // otherwise we would have a Value for it). If so, synthesize
240 // a value id.
241 for (auto &CallEdge : FS->calls())
242 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
243 assignValueId(CallEdge.first.getGUID());
244
245 // For each referenced variables in the function summary, see if the
246 // variable is represented by a GUID (as opposed to a symbol to
247 // declarations or definitions in the module). If so, synthesize a
248 // value id.
249 for (auto &RefEdge : FS->refs())
250 if (!RefEdge.haveGVs() || !RefEdge.getValue())
251 assignValueId(RefEdge.getGUID());
252 }
253 }
254
255protected:
256 void writePerModuleGlobalValueSummary();
257
258private:
259 void writePerModuleFunctionSummaryRecord(
260 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
261 unsigned ValueID, unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
262 unsigned AllocAbbrev, unsigned ContextIdAbbvId, const Function &F,
263 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
264 CallStackId &CallStackCount);
265 void writeModuleLevelReferences(const GlobalVariable &V,
266 SmallVector<uint64_t, 64> &NameVals,
267 unsigned FSModRefsAbbrev,
268 unsigned FSModVTableRefsAbbrev);
269
270 void assignValueId(GlobalValue::GUID ValGUID) {
271 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
272 }
273
274 unsigned getValueId(GlobalValue::GUID ValGUID) {
275 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
276 // Expect that any GUID value had a value Id assigned by an
277 // earlier call to assignValueId.
278 assert(VMI != GUIDToValueIdMap.end() &&
279 "GUID does not have assigned value Id");
280 return VMI->second;
281 }
282
283 // Helper to get the valueId for the type of value recorded in VI.
284 unsigned getValueId(ValueInfo VI) {
285 if (!VI.haveGVs() || !VI.getValue())
286 return getValueId(VI.getGUID());
287 return VE.getValueID(VI.getValue());
288 }
289
290 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
291};
292
293/// Class to manage the bitcode writing for a module.
294class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
295 /// True if a module hash record should be written.
296 bool GenerateHash;
297
298 /// If non-null, when GenerateHash is true, the resulting hash is written
299 /// into ModHash.
300 ModuleHash *ModHash;
301
302 SHA1 Hasher;
303
304 /// The start bit of the identification block.
305 uint64_t BitcodeStartBit;
306
307public:
308 /// Constructs a ModuleBitcodeWriter object for the given Module,
309 /// writing to the provided \p Buffer.
310 ModuleBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
311 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
312 const ModuleSummaryIndex *Index, bool GenerateHash,
313 ModuleHash *ModHash = nullptr)
314 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
315 ShouldPreserveUseListOrder, Index),
316 GenerateHash(GenerateHash), ModHash(ModHash),
317 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
318
319 /// Emit the current module to the bitstream.
320 void write();
321
322private:
323 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
324
325 size_t addToStrtab(StringRef Str);
326
327 void writeAttributeGroupTable();
328 void writeAttributeTable();
329 void writeTypeTable();
330 void writeComdats();
331 void writeValueSymbolTableForwardDecl();
332 void writeModuleInfo();
333 void writeValueAsMetadata(const ValueAsMetadata *MD,
334 SmallVectorImpl<uint64_t> &Record);
335 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
336 unsigned Abbrev);
337 unsigned createDILocationAbbrev();
338 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
339 unsigned &Abbrev);
340 unsigned createGenericDINodeAbbrev();
341 void writeGenericDINode(const GenericDINode *N,
342 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
343 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
344 unsigned Abbrev);
345 void writeDIGenericSubrange(const DIGenericSubrange *N,
346 SmallVectorImpl<uint64_t> &Record,
347 unsigned Abbrev);
348 void writeDIEnumerator(const DIEnumerator *N,
349 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
350 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
351 unsigned Abbrev);
352 void writeDIFixedPointType(const DIFixedPointType *N,
353 SmallVectorImpl<uint64_t> &Record,
354 unsigned Abbrev);
355 void writeDIStringType(const DIStringType *N,
356 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
357 void writeDIDerivedType(const DIDerivedType *N,
358 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
359 void writeDISubrangeType(const DISubrangeType *N,
360 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
361 void writeDICompositeType(const DICompositeType *N,
362 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
363 void writeDISubroutineType(const DISubroutineType *N,
364 SmallVectorImpl<uint64_t> &Record,
365 unsigned Abbrev);
366 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
367 unsigned Abbrev);
368 void writeDICompileUnit(const DICompileUnit *N,
369 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
370 void writeDISubprogram(const DISubprogram *N,
371 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
372 void writeDILexicalBlock(const DILexicalBlock *N,
373 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
374 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
375 SmallVectorImpl<uint64_t> &Record,
376 unsigned Abbrev);
377 void writeDICommonBlock(const DICommonBlock *N,
378 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
379 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
380 unsigned Abbrev);
381 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
382 unsigned Abbrev);
383 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
384 unsigned Abbrev);
385 void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record);
386 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
387 unsigned Abbrev);
388 void writeDIAssignID(const DIAssignID *N, SmallVectorImpl<uint64_t> &Record,
389 unsigned Abbrev);
390 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
391 SmallVectorImpl<uint64_t> &Record,
392 unsigned Abbrev);
393 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
394 SmallVectorImpl<uint64_t> &Record,
395 unsigned Abbrev);
396 void writeDIGlobalVariable(const DIGlobalVariable *N,
397 SmallVectorImpl<uint64_t> &Record,
398 unsigned Abbrev);
399 void writeDILocalVariable(const DILocalVariable *N,
400 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
401 void writeDILabel(const DILabel *N,
402 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
403 void writeDIExpression(const DIExpression *N,
404 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
405 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
406 SmallVectorImpl<uint64_t> &Record,
407 unsigned Abbrev);
408 void writeDIObjCProperty(const DIObjCProperty *N,
409 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
410 void writeDIImportedEntity(const DIImportedEntity *N,
411 SmallVectorImpl<uint64_t> &Record,
412 unsigned Abbrev);
413 unsigned createNamedMetadataAbbrev();
414 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
415 unsigned createMetadataStringsAbbrev();
416 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
417 SmallVectorImpl<uint64_t> &Record);
418 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
419 SmallVectorImpl<uint64_t> &Record,
420 std::vector<unsigned> *MDAbbrevs = nullptr,
421 std::vector<uint64_t> *IndexPos = nullptr);
422 void writeModuleMetadata();
423 void writeFunctionMetadata(const Function &F);
424 void writeFunctionMetadataAttachment(const Function &F);
425 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
426 const GlobalObject &GO);
427 void writeModuleMetadataKinds();
428 void writeOperandBundleTags();
429 void writeSyncScopeNames();
430 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
431 void writeModuleConstants();
432 bool pushValueAndType(const Value *V, unsigned InstID,
433 SmallVectorImpl<unsigned> &Vals);
434 bool pushValueOrMetadata(const Value *V, unsigned InstID,
435 SmallVectorImpl<unsigned> &Vals);
436 void writeOperandBundles(const CallBase &CB, unsigned InstID);
437 void pushValue(const Value *V, unsigned InstID,
438 SmallVectorImpl<unsigned> &Vals);
439 void pushValueSigned(const Value *V, unsigned InstID,
440 SmallVectorImpl<uint64_t> &Vals);
441 void writeInstruction(const Instruction &I, unsigned InstID,
442 SmallVectorImpl<unsigned> &Vals);
443 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
444 void writeGlobalValueSymbolTable(
445 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
446 void writeUseList(UseListOrder &&Order);
447 void writeUseListBlock(const Function *F);
448 void
449 writeFunction(const Function &F,
450 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
451 void writeBlockInfo();
452 void writeModuleHash(StringRef View);
453
454 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
455 return unsigned(SSID);
456 }
457
458 unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
459};
460
461/// Class to manage the bitcode writing for a combined index.
462class IndexBitcodeWriter : public BitcodeWriterBase {
463 /// The combined index to write to bitcode.
464 const ModuleSummaryIndex &Index;
465
466 /// When writing combined summaries, provides the set of global value
467 /// summaries for which the value (function, function alias, etc) should be
468 /// imported as a declaration.
469 const GVSummaryPtrSet *DecSummaries = nullptr;
470
471 /// When writing a subset of the index for distributed backends, client
472 /// provides a map of modules to the corresponding GUIDs/summaries to write.
473 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex;
474
475 /// Map that holds the correspondence between the GUID used in the combined
476 /// index and a value id generated by this class to use in references.
477 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
478
479 // The stack ids used by this index, which will be a subset of those in
480 // the full index in the case of distributed indexes.
481 std::vector<uint64_t> StackIds;
482
483 // Keep a map of the stack id indices used by records being written for this
484 // index to the index of the corresponding stack id in the above StackIds
485 // vector. Ensures we write each referenced stack id once.
486 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
487
488 /// Tracks the last value id recorded in the GUIDToValueMap.
489 unsigned GlobalValueId = 0;
490
491 /// Tracks the assignment of module paths in the module path string table to
492 /// an id assigned for use in summary references to the module path.
493 DenseMap<StringRef, uint64_t> ModuleIdMap;
494
495public:
496 /// Constructs a IndexBitcodeWriter object for the given combined index,
497 /// writing to the provided \p Buffer. When writing a subset of the index
498 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
499 /// If provided, \p DecSummaries specifies the set of summaries for which
500 /// the corresponding functions or aliased functions should be imported as a
501 /// declaration (but not definition) for each module.
502 IndexBitcodeWriter(
503 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
504 const ModuleSummaryIndex &Index,
505 const GVSummaryPtrSet *DecSummaries = nullptr,
506 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex = nullptr)
507 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
508 DecSummaries(DecSummaries),
509 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
510
511 // See if the StackIdIndex was already added to the StackId map and
512 // vector. If not, record it.
513 auto RecordStackIdReference = [&](unsigned StackIdIndex) {
514 // If the StackIdIndex is not yet in the map, the below insert ensures
515 // that it will point to the new StackIds vector entry we push to just
516 // below.
517 auto Inserted =
518 StackIdIndicesToIndex.insert({StackIdIndex, StackIds.size()});
519 if (Inserted.second)
520 StackIds.push_back(Index.getStackIdAtIndex(StackIdIndex));
521 };
522
523 // Assign unique value ids to all summaries to be written, for use
524 // in writing out the call graph edges. Save the mapping from GUID
525 // to the new global value id to use when writing those edges, which
526 // are currently saved in the index in terms of GUID.
527 forEachSummary([&](GVInfo I, bool IsAliasee) {
528 GUIDToValueIdMap[I.first] = ++GlobalValueId;
529 // If this is invoked for an aliasee, we want to record the above mapping,
530 // but not the information needed for its summary entry (if the aliasee is
531 // to be imported, we will invoke this separately with IsAliasee=false).
532 if (IsAliasee)
533 return;
534 auto *FS = dyn_cast<FunctionSummary>(I.second);
535 if (!FS)
536 return;
537 // Record all stack id indices actually used in the summary entries being
538 // written, so that we can compact them in the case of distributed ThinLTO
539 // indexes.
540 for (auto &CI : FS->callsites()) {
541 // If the stack id list is empty, this callsite info was synthesized for
542 // a missing tail call frame. Ensure that the callee's GUID gets a value
543 // id. Normally we only generate these for defined summaries, which in
544 // the case of distributed ThinLTO is only the functions already defined
545 // in the module or that we want to import. We don't bother to include
546 // all the callee symbols as they aren't normally needed in the backend.
547 // However, for the synthesized callsite infos we do need the callee
548 // GUID in the backend so that we can correlate the identified callee
549 // with this callsite info (which for non-tail calls is done by the
550 // ordering of the callsite infos and verified via stack ids).
551 if (CI.StackIdIndices.empty()) {
552 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
553 continue;
554 }
555 for (auto Idx : CI.StackIdIndices)
556 RecordStackIdReference(Idx);
557 }
559 for (auto &AI : FS->allocs())
560 for (auto &MIB : AI.MIBs)
561 for (auto Idx : MIB.StackIdIndices)
562 RecordStackIdReference(Idx);
563 }
564 });
565 }
566
567 /// The below iterator returns the GUID and associated summary.
568 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
569
570 /// Calls the callback for each value GUID and summary to be written to
571 /// bitcode. This hides the details of whether they are being pulled from the
572 /// entire index or just those in a provided ModuleToSummariesForIndex map.
573 template<typename Functor>
574 void forEachSummary(Functor Callback) {
575 if (ModuleToSummariesForIndex) {
576 for (auto &M : *ModuleToSummariesForIndex)
577 for (auto &Summary : M.second) {
578 Callback(Summary, false);
579 // Ensure aliasee is handled, e.g. for assigning a valueId,
580 // even if we are not importing the aliasee directly (the
581 // imported alias will contain a copy of aliasee).
582 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
583 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
584 }
585 } else {
586 for (auto &Summaries : Index)
587 for (auto &Summary : Summaries.second.getSummaryList())
588 Callback({Summaries.first, Summary.get()}, false);
589 }
590 }
591
592 /// Calls the callback for each entry in the modulePaths StringMap that
593 /// should be written to the module path string table. This hides the details
594 /// of whether they are being pulled from the entire index or just those in a
595 /// provided ModuleToSummariesForIndex map.
596 template <typename Functor> void forEachModule(Functor Callback) {
597 if (ModuleToSummariesForIndex) {
598 for (const auto &M : *ModuleToSummariesForIndex) {
599 const auto &MPI = Index.modulePaths().find(M.first);
600 if (MPI == Index.modulePaths().end()) {
601 // This should only happen if the bitcode file was empty, in which
602 // case we shouldn't be importing (the ModuleToSummariesForIndex
603 // would only include the module we are writing and index for).
604 assert(ModuleToSummariesForIndex->size() == 1);
605 continue;
606 }
607 Callback(*MPI);
608 }
609 } else {
610 // Since StringMap iteration order isn't guaranteed, order by path string
611 // first.
612 // FIXME: Make this a vector of StringMapEntry instead to avoid the later
613 // map lookup.
614 std::vector<StringRef> ModulePaths;
615 for (auto &[ModPath, _] : Index.modulePaths())
616 ModulePaths.push_back(ModPath);
617 llvm::sort(ModulePaths);
618 for (auto &ModPath : ModulePaths)
619 Callback(*Index.modulePaths().find(ModPath));
620 }
621 }
622
623 /// Main entry point for writing a combined index to bitcode.
624 void write();
625
626private:
627 void writeModStrings();
628 void writeCombinedGlobalValueSummary();
629
630 std::optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
631 auto VMI = GUIDToValueIdMap.find(ValGUID);
632 if (VMI == GUIDToValueIdMap.end())
633 return std::nullopt;
634 return VMI->second;
635 }
636
637 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
638};
639
640} // end anonymous namespace
641
642static unsigned getEncodedCastOpcode(unsigned Opcode) {
643 switch (Opcode) {
644 default: llvm_unreachable("Unknown cast instruction!");
645 case Instruction::Trunc : return bitc::CAST_TRUNC;
646 case Instruction::ZExt : return bitc::CAST_ZEXT;
647 case Instruction::SExt : return bitc::CAST_SEXT;
648 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
649 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
650 case Instruction::UIToFP : return bitc::CAST_UITOFP;
651 case Instruction::SIToFP : return bitc::CAST_SITOFP;
652 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
653 case Instruction::FPExt : return bitc::CAST_FPEXT;
654 case Instruction::PtrToAddr: return bitc::CAST_PTRTOADDR;
655 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
656 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
657 case Instruction::BitCast : return bitc::CAST_BITCAST;
658 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
659 }
660}
661
662static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
663 switch (Opcode) {
664 default: llvm_unreachable("Unknown binary instruction!");
665 case Instruction::FNeg: return bitc::UNOP_FNEG;
666 }
667}
668
669static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
670 switch (Opcode) {
671 default: llvm_unreachable("Unknown binary instruction!");
672 case Instruction::Add:
673 case Instruction::FAdd: return bitc::BINOP_ADD;
674 case Instruction::Sub:
675 case Instruction::FSub: return bitc::BINOP_SUB;
676 case Instruction::Mul:
677 case Instruction::FMul: return bitc::BINOP_MUL;
678 case Instruction::UDiv: return bitc::BINOP_UDIV;
679 case Instruction::FDiv:
680 case Instruction::SDiv: return bitc::BINOP_SDIV;
681 case Instruction::URem: return bitc::BINOP_UREM;
682 case Instruction::FRem:
683 case Instruction::SRem: return bitc::BINOP_SREM;
684 case Instruction::Shl: return bitc::BINOP_SHL;
685 case Instruction::LShr: return bitc::BINOP_LSHR;
686 case Instruction::AShr: return bitc::BINOP_ASHR;
687 case Instruction::And: return bitc::BINOP_AND;
688 case Instruction::Or: return bitc::BINOP_OR;
689 case Instruction::Xor: return bitc::BINOP_XOR;
690 }
691}
692
693static unsigned getEncodedRMWOperation(const AtomicRMWInst &I) {
694 unsigned Encoding = 0;
695 switch (I.getOperation()) {
696 default: llvm_unreachable("Unknown RMW operation!");
698 Encoding = bitc::RMW_XCHG;
699 break;
701 Encoding = bitc::RMW_ADD;
702 break;
704 Encoding = bitc::RMW_SUB;
705 break;
707 Encoding = bitc::RMW_AND;
708 break;
710 Encoding = bitc::RMW_NAND;
711 break;
713 Encoding = bitc::RMW_OR;
714 break;
716 Encoding = bitc::RMW_XOR;
717 break;
719 Encoding = bitc::RMW_MAX;
720 break;
722 Encoding = bitc::RMW_MIN;
723 break;
725 Encoding = bitc::RMW_UMAX;
726 break;
728 Encoding = bitc::RMW_UMIN;
729 break;
731 Encoding = bitc::RMW_FADD;
732 break;
734 Encoding = bitc::RMW_FSUB;
735 break;
737 Encoding = bitc::RMW_FMAX;
738 break;
740 Encoding = bitc::RMW_FMIN;
741 break;
743 Encoding = bitc::RMW_FMAXIMUM;
744 break;
746 Encoding = bitc::RMW_FMINIMUM;
747 break;
749 Encoding = bitc::RMW_FMAXIMUMNUM;
750 break;
752 Encoding = bitc::RMW_FMINIMUMNUM;
753 break;
755 Encoding = bitc::RMW_UINC_WRAP;
756 break;
758 Encoding = bitc::RMW_UDEC_WRAP;
759 break;
761 Encoding = bitc::RMW_USUB_COND;
762 break;
764 Encoding = bitc::RMW_USUB_SAT;
765 break;
766 }
767
768 if (I.isElementwise())
769 Encoding |= bitc::RMW_ELEMENTWISE_FLAG;
770 return Encoding;
771}
772
785
786static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
787 StringRef Str, unsigned AbbrevToUse) {
789
790 // Code: [strchar x N]
791 for (char C : Str) {
792 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
793 AbbrevToUse = 0;
794 Vals.push_back(C);
795 }
796
797 // Emit the finished record.
798 Stream.EmitRecord(Code, Vals, AbbrevToUse);
799}
800
802 switch (Kind) {
803 case Attribute::Alignment:
805 case Attribute::AllocAlign:
807 case Attribute::AllocSize:
809 case Attribute::AlwaysInline:
811 case Attribute::Builtin:
813 case Attribute::ByVal:
815 case Attribute::Convergent:
817 case Attribute::InAlloca:
819 case Attribute::Cold:
821 case Attribute::DisableSanitizerInstrumentation:
823 case Attribute::FnRetThunkExtern:
825 case Attribute::Flatten:
827 case Attribute::Hot:
828 return bitc::ATTR_KIND_HOT;
829 case Attribute::ElementType:
831 case Attribute::HybridPatchable:
833 case Attribute::InlineHint:
835 case Attribute::InReg:
837 case Attribute::JumpTable:
839 case Attribute::MinSize:
841 case Attribute::AllocatedPointer:
843 case Attribute::AllocKind:
845 case Attribute::Memory:
847 case Attribute::NoFPClass:
849 case Attribute::Naked:
851 case Attribute::Nest:
853 case Attribute::NoAlias:
855 case Attribute::NoBuiltin:
857 case Attribute::NoCallback:
859 case Attribute::NoDivergenceSource:
861 case Attribute::NoDuplicate:
863 case Attribute::NoFree:
865 case Attribute::NoImplicitFloat:
867 case Attribute::NoInline:
869 case Attribute::NoRecurse:
871 case Attribute::NoMerge:
873 case Attribute::NonLazyBind:
875 case Attribute::NonNull:
877 case Attribute::Dereferenceable:
879 case Attribute::DereferenceableOrNull:
881 case Attribute::NoRedZone:
883 case Attribute::NoReturn:
885 case Attribute::NoSync:
887 case Attribute::NoCfCheck:
889 case Attribute::NoProfile:
891 case Attribute::SkipProfile:
893 case Attribute::NoUnwind:
895 case Attribute::NoSanitizeBounds:
897 case Attribute::NoSanitizeCoverage:
899 case Attribute::NullPointerIsValid:
901 case Attribute::OptimizeForDebugging:
903 case Attribute::OptForFuzzing:
905 case Attribute::OptimizeForSize:
907 case Attribute::OptimizeNone:
909 case Attribute::ReadNone:
911 case Attribute::ReadOnly:
913 case Attribute::Returned:
915 case Attribute::ReturnsTwice:
917 case Attribute::SExt:
919 case Attribute::Speculatable:
921 case Attribute::StackAlignment:
923 case Attribute::StackProtect:
925 case Attribute::StackProtectReq:
927 case Attribute::StackProtectStrong:
929 case Attribute::SafeStack:
931 case Attribute::ShadowCallStack:
933 case Attribute::StrictFP:
935 case Attribute::StructRet:
937 case Attribute::SanitizeAddress:
939 case Attribute::SanitizeAllocToken:
941 case Attribute::SanitizeHWAddress:
943 case Attribute::SanitizeThread:
945 case Attribute::SanitizeType:
947 case Attribute::SanitizeMemory:
949 case Attribute::SanitizeNumericalStability:
951 case Attribute::SanitizeRealtime:
953 case Attribute::SanitizeRealtimeBlocking:
955 case Attribute::SpeculativeLoadHardening:
957 case Attribute::SwiftError:
959 case Attribute::SwiftSelf:
961 case Attribute::SwiftAsync:
963 case Attribute::UWTable:
965 case Attribute::VScaleRange:
967 case Attribute::WillReturn:
969 case Attribute::WriteOnly:
971 case Attribute::ZExt:
973 case Attribute::ImmArg:
975 case Attribute::SanitizeMemTag:
977 case Attribute::Preallocated:
979 case Attribute::NoUndef:
981 case Attribute::ByRef:
983 case Attribute::MustProgress:
985 case Attribute::PresplitCoroutine:
987 case Attribute::Writable:
989 case Attribute::CoroDestroyOnlyWhenComplete:
991 case Attribute::CoroElideSafe:
993 case Attribute::DeadOnUnwind:
995 case Attribute::Range:
997 case Attribute::Initializes:
999 case Attribute::NoExt:
1001 case Attribute::Captures:
1003 case Attribute::DeadOnReturn:
1005 case Attribute::NoCreateUndefOrPoison:
1007 case Attribute::DenormalFPEnv:
1009 case Attribute::NoOutline:
1012 llvm_unreachable("Can not encode end-attribute kinds marker.");
1013 case Attribute::None:
1014 llvm_unreachable("Can not encode none-attribute.");
1017 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
1018 }
1019
1020 llvm_unreachable("Trying to encode unknown attribute");
1021}
1022
1024 if ((int64_t)V >= 0)
1025 Vals.push_back(V << 1);
1026 else
1027 Vals.push_back((-V << 1) | 1);
1028}
1029
1031 // We have an arbitrary precision integer value to write whose
1032 // bit width is > 64. However, in canonical unsigned integer
1033 // format it is likely that the high bits are going to be zero.
1034 // So, we only write the number of active words.
1035 unsigned NumWords = A.getActiveWords();
1036 const uint64_t *RawData = A.getRawData();
1037 for (unsigned i = 0; i < NumWords; i++)
1038 emitSignedInt64(Vals, RawData[i]);
1039}
1040
1042 const ConstantRange &CR, bool EmitBitWidth) {
1043 unsigned BitWidth = CR.getBitWidth();
1044 if (EmitBitWidth)
1045 Record.push_back(BitWidth);
1046 if (BitWidth > 64) {
1047 Record.push_back(CR.getLower().getActiveWords() |
1048 (uint64_t(CR.getUpper().getActiveWords()) << 32));
1051 } else {
1054 }
1055}
1056
1057void ModuleBitcodeWriter::writeAttributeGroupTable() {
1058 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
1059 VE.getAttributeGroups();
1060 if (AttrGrps.empty()) return;
1061
1063
1064 SmallVector<uint64_t, 64> Record;
1065 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
1066 unsigned AttrListIndex = Pair.first;
1067 AttributeSet AS = Pair.second;
1068 Record.push_back(VE.getAttributeGroupID(Pair));
1069 Record.push_back(AttrListIndex);
1070
1071 for (Attribute Attr : AS) {
1072 if (Attr.isEnumAttribute()) {
1073 Record.push_back(0);
1074 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1075 } else if (Attr.isIntAttribute()) {
1076 Record.push_back(1);
1077 Attribute::AttrKind Kind = Attr.getKindAsEnum();
1078 Record.push_back(getAttrKindEncoding(Kind));
1079 if (Kind == Attribute::Memory) {
1080 // Version field for upgrading old memory effects.
1081 const uint64_t Version = 1;
1082 Record.push_back((Version << 56) | Attr.getValueAsInt());
1083 } else {
1084 Record.push_back(Attr.getValueAsInt());
1085 }
1086 } else if (Attr.isStringAttribute()) {
1087 StringRef Kind = Attr.getKindAsString();
1088 StringRef Val = Attr.getValueAsString();
1089
1090 Record.push_back(Val.empty() ? 3 : 4);
1091 Record.append(Kind.begin(), Kind.end());
1092 Record.push_back(0);
1093 if (!Val.empty()) {
1094 Record.append(Val.begin(), Val.end());
1095 Record.push_back(0);
1096 }
1097 } else if (Attr.isTypeAttribute()) {
1098 Type *Ty = Attr.getValueAsType();
1099 Record.push_back(Ty ? 6 : 5);
1100 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1101 if (Ty)
1102 Record.push_back(VE.getTypeID(Attr.getValueAsType()));
1103 } else if (Attr.isConstantRangeAttribute()) {
1104 Record.push_back(7);
1105 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1106 emitConstantRange(Record, Attr.getValueAsConstantRange(),
1107 /*EmitBitWidth=*/true);
1108 } else {
1109 assert(Attr.isConstantRangeListAttribute());
1110 Record.push_back(8);
1111 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1112 ArrayRef<ConstantRange> Val = Attr.getValueAsConstantRangeList();
1113 Record.push_back(Val.size());
1114 Record.push_back(Val[0].getBitWidth());
1115 for (auto &CR : Val)
1116 emitConstantRange(Record, CR, /*EmitBitWidth=*/false);
1117 }
1118 }
1119
1121 Record.clear();
1122 }
1123
1124 Stream.ExitBlock();
1125}
1126
1127void ModuleBitcodeWriter::writeAttributeTable() {
1128 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
1129 if (Attrs.empty()) return;
1130
1132
1133 SmallVector<uint64_t, 64> Record;
1134 for (const AttributeList &AL : Attrs) {
1135 for (unsigned i : AL.indexes()) {
1136 AttributeSet AS = AL.getAttributes(i);
1137 if (AS.hasAttributes())
1138 Record.push_back(VE.getAttributeGroupID({i, AS}));
1139 }
1140
1141 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
1142 Record.clear();
1143 }
1144
1145 Stream.ExitBlock();
1146}
1147
1148/// WriteTypeTable - Write out the type table for a module.
1149void ModuleBitcodeWriter::writeTypeTable() {
1150 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
1151
1152 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
1153 SmallVector<uint64_t, 64> TypeVals;
1154
1155 uint64_t NumBits = VE.computeBitsRequiredForTypeIndices();
1156
1157 // Abbrev for TYPE_CODE_OPAQUE_POINTER.
1158 auto Abbv = std::make_shared<BitCodeAbbrev>();
1159 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_OPAQUE_POINTER));
1160 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
1161 unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1162
1163 // Abbrev for TYPE_CODE_FUNCTION.
1164 Abbv = std::make_shared<BitCodeAbbrev>();
1165 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
1166 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
1167 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1168 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1169 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1170
1171 // Abbrev for TYPE_CODE_STRUCT_ANON.
1172 Abbv = std::make_shared<BitCodeAbbrev>();
1173 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
1174 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1175 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1176 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1177 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1178
1179 // Abbrev for TYPE_CODE_STRUCT_NAME.
1180 Abbv = std::make_shared<BitCodeAbbrev>();
1181 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
1182 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1183 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1184 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1185
1186 // Abbrev for TYPE_CODE_STRUCT_NAMED.
1187 Abbv = std::make_shared<BitCodeAbbrev>();
1188 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
1189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1191 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1192 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1193
1194 // Abbrev for TYPE_CODE_ARRAY.
1195 Abbv = std::make_shared<BitCodeAbbrev>();
1196 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
1197 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
1198 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1199 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1200
1201 // Emit an entry count so the reader can reserve space.
1202 TypeVals.push_back(TypeList.size());
1203 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
1204 TypeVals.clear();
1205
1206 // Loop over all of the types, emitting each in turn.
1207 for (Type *T : TypeList) {
1208 int AbbrevToUse = 0;
1209 unsigned Code = 0;
1210
1211 switch (T->getTypeID()) {
1212 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
1213 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
1214 case Type::BFloatTyID: Code = bitc::TYPE_CODE_BFLOAT; break;
1215 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
1216 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
1217 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
1218 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
1219 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
1220 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
1221 case Type::MetadataTyID:
1223 break;
1224 case Type::X86_AMXTyID: Code = bitc::TYPE_CODE_X86_AMX; break;
1225 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
1226 case Type::ByteTyID:
1227 // BYTE: [width]
1229 TypeVals.push_back(T->getByteBitWidth());
1230 break;
1231 case Type::IntegerTyID:
1232 // INTEGER: [width]
1235 break;
1236 case Type::PointerTyID: {
1238 unsigned AddressSpace = PTy->getAddressSpace();
1239 // OPAQUE_POINTER: [address space]
1241 TypeVals.push_back(AddressSpace);
1242 if (AddressSpace == 0)
1243 AbbrevToUse = OpaquePtrAbbrev;
1244 break;
1245 }
1246 case Type::FunctionTyID: {
1247 FunctionType *FT = cast<FunctionType>(T);
1248 // FUNCTION: [isvararg, retty, paramty x N]
1250 TypeVals.push_back(FT->isVarArg());
1251 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
1252 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1253 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
1254 AbbrevToUse = FunctionAbbrev;
1255 break;
1256 }
1257 case Type::StructTyID: {
1258 StructType *ST = cast<StructType>(T);
1259 // STRUCT: [ispacked, eltty x N]
1260 TypeVals.push_back(ST->isPacked());
1261 // Output all of the element types.
1262 for (Type *ET : ST->elements())
1263 TypeVals.push_back(VE.getTypeID(ET));
1264
1265 if (ST->isLiteral()) {
1267 AbbrevToUse = StructAnonAbbrev;
1268 } else {
1269 if (ST->isOpaque()) {
1271 } else {
1273 AbbrevToUse = StructNamedAbbrev;
1274 }
1275
1276 // Emit the name if it is present.
1277 if (!ST->getName().empty())
1279 StructNameAbbrev);
1280 }
1281 break;
1282 }
1283 case Type::ArrayTyID: {
1285 // ARRAY: [numelts, eltty]
1287 TypeVals.push_back(AT->getNumElements());
1288 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1289 AbbrevToUse = ArrayAbbrev;
1290 break;
1291 }
1292 case Type::FixedVectorTyID:
1293 case Type::ScalableVectorTyID: {
1295 // VECTOR [numelts, eltty] or
1296 // [numelts, eltty, scalable]
1298 TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1299 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1301 TypeVals.push_back(true);
1302 break;
1303 }
1304 case Type::TargetExtTyID: {
1305 TargetExtType *TET = cast<TargetExtType>(T);
1308 StructNameAbbrev);
1309 TypeVals.push_back(TET->getNumTypeParameters());
1310 for (Type *InnerTy : TET->type_params())
1311 TypeVals.push_back(VE.getTypeID(InnerTy));
1312 llvm::append_range(TypeVals, TET->int_params());
1313 break;
1314 }
1315 case Type::TypedPointerTyID:
1316 llvm_unreachable("Typed pointers cannot be added to IR modules");
1317 }
1318
1319 // Emit the finished record.
1320 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1321 TypeVals.clear();
1322 }
1323
1324 Stream.ExitBlock();
1325}
1326
1328 switch (Linkage) {
1330 return 0;
1332 return 16;
1334 return 2;
1336 return 3;
1338 return 18;
1340 return 7;
1342 return 8;
1344 return 9;
1346 return 17;
1348 return 19;
1350 return 12;
1351 }
1352 llvm_unreachable("Invalid linkage");
1353}
1354
1355static unsigned getEncodedLinkage(const GlobalValue &GV) {
1356 return getEncodedLinkage(GV.getLinkage());
1357}
1358
1360 uint64_t RawFlags = 0;
1361 RawFlags |= Flags.ReadNone;
1362 RawFlags |= (Flags.ReadOnly << 1);
1363 RawFlags |= (Flags.NoRecurse << 2);
1364 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1365 RawFlags |= (Flags.NoInline << 4);
1366 RawFlags |= (Flags.AlwaysInline << 5);
1367 RawFlags |= (Flags.NoUnwind << 6);
1368 RawFlags |= (Flags.MayThrow << 7);
1369 RawFlags |= (Flags.HasUnknownCall << 8);
1370 RawFlags |= (Flags.MustBeUnreachable << 9);
1371 return RawFlags;
1372}
1373
1374// Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1375// in BitcodeReader.cpp.
1377 bool ImportAsDecl = false) {
1378 uint64_t RawFlags = 0;
1379
1380 RawFlags |= Flags.NotEligibleToImport; // bool
1381 RawFlags |= (Flags.Live << 1);
1382 RawFlags |= (Flags.DSOLocal << 2);
1383 RawFlags |= (Flags.CanAutoHide << 3);
1384
1385 // Linkage don't need to be remapped at that time for the summary. Any future
1386 // change to the getEncodedLinkage() function will need to be taken into
1387 // account here as well.
1388 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1389
1390 RawFlags |= (Flags.Visibility << 8); // 2 bits
1391
1392 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1393 RawFlags |= (ImportType << 10); // 1 bit
1394
1395 RawFlags |= (Flags.NoRenameOnPromotion << 11); // 1 bit
1396
1397 return RawFlags;
1398}
1399
1401 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1402 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1403 return RawFlags;
1404}
1405
1407 uint64_t RawFlags = 0;
1408
1409 RawFlags |= CI.Hotness; // 3 bits
1410 RawFlags |= (CI.HasTailCall << 3); // 1 bit
1411
1412 return RawFlags;
1413}
1414
1415static unsigned getEncodedVisibility(const GlobalValue &GV) {
1416 switch (GV.getVisibility()) {
1417 case GlobalValue::DefaultVisibility: return 0;
1418 case GlobalValue::HiddenVisibility: return 1;
1419 case GlobalValue::ProtectedVisibility: return 2;
1420 }
1421 llvm_unreachable("Invalid visibility");
1422}
1423
1424static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1425 switch (GV.getDLLStorageClass()) {
1426 case GlobalValue::DefaultStorageClass: return 0;
1429 }
1430 llvm_unreachable("Invalid DLL storage class");
1431}
1432
1433static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1434 switch (GV.getThreadLocalMode()) {
1435 case GlobalVariable::NotThreadLocal: return 0;
1439 case GlobalVariable::LocalExecTLSModel: return 4;
1440 }
1441 llvm_unreachable("Invalid TLS model");
1442}
1443
1444static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1445 switch (C.getSelectionKind()) {
1446 case Comdat::Any:
1448 case Comdat::ExactMatch:
1450 case Comdat::Largest:
1454 case Comdat::SameSize:
1456 }
1457 llvm_unreachable("Invalid selection kind");
1458}
1459
1460static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1461 switch (GV.getUnnamedAddr()) {
1462 case GlobalValue::UnnamedAddr::None: return 0;
1463 case GlobalValue::UnnamedAddr::Local: return 2;
1464 case GlobalValue::UnnamedAddr::Global: return 1;
1465 }
1466 llvm_unreachable("Invalid unnamed_addr");
1467}
1468
1469size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1470 if (GenerateHash)
1471 Hasher.update(Str);
1472 return StrtabBuilder.add(Str);
1473}
1474
1475void ModuleBitcodeWriter::writeComdats() {
1477 for (const Comdat *C : VE.getComdats()) {
1478 // COMDAT: [strtab offset, strtab size, selection_kind]
1479 Vals.push_back(addToStrtab(C->getName()));
1480 Vals.push_back(C->getName().size());
1482 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1483 Vals.clear();
1484 }
1485}
1486
1487/// Write a record that will eventually hold the word offset of the
1488/// module-level VST. For now the offset is 0, which will be backpatched
1489/// after the real VST is written. Saves the bit offset to backpatch.
1490void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1491 // Write a placeholder value in for the offset of the real VST,
1492 // which is written after the function blocks so that it can include
1493 // the offset of each function. The placeholder offset will be
1494 // updated when the real VST is written.
1495 auto Abbv = std::make_shared<BitCodeAbbrev>();
1496 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1497 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1498 // hold the real VST offset. Must use fixed instead of VBR as we don't
1499 // know how many VBR chunks to reserve ahead of time.
1500 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1501 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1502
1503 // Emit the placeholder
1504 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
1505 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1506
1507 // Compute and save the bit offset to the placeholder, which will be
1508 // patched when the real VST is written. We can simply subtract the 32-bit
1509 // fixed size from the current bit number to get the location to backpatch.
1510 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1511}
1512
1514
1515/// Determine the encoding to use for the given string name and length.
1517 bool isChar6 = true;
1518 for (char C : Str) {
1519 if (isChar6)
1520 isChar6 = BitCodeAbbrevOp::isChar6(C);
1521 if ((unsigned char)C & 128)
1522 // don't bother scanning the rest.
1523 return SE_Fixed8;
1524 }
1525 if (isChar6)
1526 return SE_Char6;
1527 return SE_Fixed7;
1528}
1529
1530static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
1531 "Sanitizer Metadata is too large for naive serialization.");
1532static unsigned
1534 return Meta.NoAddress | (Meta.NoHWAddress << 1) |
1535 (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
1536}
1537
1538/// Emit top-level description of module, including target triple, inline asm,
1539/// descriptors for global variables, and function prototype info.
1540/// Returns the bit offset to backpatch with the location of the real VST.
1541void ModuleBitcodeWriter::writeModuleInfo() {
1542 // Emit various pieces of data attached to a module.
1543 if (!M.getTargetTriple().empty())
1545 M.getTargetTriple().str(), 0 /*TODO*/);
1546 const std::string &DL = M.getDataLayoutStr();
1547 if (!DL.empty())
1549 if (!M.getModuleInlineAsm().empty())
1550 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1551 0 /*TODO*/);
1552
1553 // Emit information about sections and GC, computing how many there are. Also
1554 // compute the maximum alignment value.
1555 std::map<std::string, unsigned> SectionMap;
1556 std::map<std::string, unsigned> GCMap;
1557 MaybeAlign MaxGVarAlignment;
1558 unsigned MaxGlobalType = 0;
1559 for (const GlobalVariable &GV : M.globals()) {
1560 if (MaybeAlign A = GV.getAlign())
1561 MaxGVarAlignment = !MaxGVarAlignment ? *A : std::max(*MaxGVarAlignment, *A);
1562 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1563 if (GV.hasSection()) {
1564 // Give section names unique ID's.
1565 unsigned &Entry = SectionMap[std::string(GV.getSection())];
1566 if (!Entry) {
1567 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1568 0 /*TODO*/);
1569 Entry = SectionMap.size();
1570 }
1571 }
1572 }
1573 for (const Function &F : M) {
1574 if (F.hasSection()) {
1575 // Give section names unique ID's.
1576 unsigned &Entry = SectionMap[std::string(F.getSection())];
1577 if (!Entry) {
1579 0 /*TODO*/);
1580 Entry = SectionMap.size();
1581 }
1582 }
1583 if (F.hasGC()) {
1584 // Same for GC names.
1585 unsigned &Entry = GCMap[F.getGC()];
1586 if (!Entry) {
1588 0 /*TODO*/);
1589 Entry = GCMap.size();
1590 }
1591 }
1592 }
1593
1594 // Emit abbrev for globals, now that we know # sections and max alignment.
1595 unsigned SimpleGVarAbbrev = 0;
1596 if (!M.global_empty()) {
1597 // Add an abbrev for common globals with no visibility or thread localness.
1598 auto Abbv = std::make_shared<BitCodeAbbrev>();
1599 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1600 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1601 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1602 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1603 Log2_32_Ceil(MaxGlobalType+1)));
1604 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1605 //| explicitType << 1
1606 //| constant
1607 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1608 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1609 if (!MaxGVarAlignment) // Alignment.
1610 Abbv->Add(BitCodeAbbrevOp(0));
1611 else {
1612 unsigned MaxEncAlignment = getEncodedAlign(MaxGVarAlignment);
1613 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1614 Log2_32_Ceil(MaxEncAlignment+1)));
1615 }
1616 if (SectionMap.empty()) // Section.
1617 Abbv->Add(BitCodeAbbrevOp(0));
1618 else
1619 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1620 Log2_32_Ceil(SectionMap.size()+1)));
1621 // Don't bother emitting vis + thread local.
1622 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1623 }
1624
1626 // Emit the module's source file name.
1627 {
1628 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1629 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1630 if (Bits == SE_Char6)
1631 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1632 else if (Bits == SE_Fixed7)
1633 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1634
1635 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1636 auto Abbv = std::make_shared<BitCodeAbbrev>();
1637 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1638 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1639 Abbv->Add(AbbrevOpToUse);
1640 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1641
1642 for (const auto P : M.getSourceFileName())
1643 Vals.push_back((unsigned char)P);
1644
1645 // Emit the finished record.
1646 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1647 Vals.clear();
1648 }
1649
1650 // Emit the global variable information.
1651 for (const GlobalVariable &GV : M.globals()) {
1652 unsigned AbbrevToUse = 0;
1653
1654 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1655 // linkage, alignment, section, visibility, threadlocal,
1656 // unnamed_addr, externally_initialized, dllstorageclass,
1657 // comdat, attributes, DSO_Local, GlobalSanitizer, code_model]
1658 Vals.push_back(addToStrtab(GV.getName()));
1659 Vals.push_back(GV.getName().size());
1660 Vals.push_back(VE.getTypeID(GV.getValueType()));
1661 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1662 Vals.push_back(GV.isDeclaration() ? 0 :
1663 (VE.getValueID(GV.getInitializer()) + 1));
1664 Vals.push_back(getEncodedLinkage(GV));
1665 Vals.push_back(getEncodedAlign(GV.getAlign()));
1666 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1667 : 0);
1668 if (GV.isThreadLocal() ||
1669 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1670 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1671 GV.isExternallyInitialized() ||
1672 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1673 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1674 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1678 Vals.push_back(GV.isExternallyInitialized());
1680 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1681
1682 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1683 Vals.push_back(VE.getAttributeListID(AL));
1684
1685 Vals.push_back(GV.isDSOLocal());
1686 Vals.push_back(addToStrtab(GV.getPartition()));
1687 Vals.push_back(GV.getPartition().size());
1688
1689 Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
1690 GV.getSanitizerMetadata())
1691 : 0));
1692 Vals.push_back(GV.getCodeModelRaw());
1693 } else {
1694 AbbrevToUse = SimpleGVarAbbrev;
1695 }
1696
1697 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1698 Vals.clear();
1699 }
1700
1701 // Emit the function proto information.
1702 for (const Function &F : M) {
1703 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1704 // linkage, paramattrs, alignment, section, visibility, gc,
1705 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1706 // prefixdata, personalityfn, DSO_Local, addrspace,
1707 // partition_strtab, partition_size, prefalign]
1708 Vals.push_back(addToStrtab(F.getName()));
1709 Vals.push_back(F.getName().size());
1710 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1711 Vals.push_back(F.getCallingConv());
1712 Vals.push_back(F.isDeclaration());
1714 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1715 Vals.push_back(getEncodedAlign(F.getAlign()));
1716 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1717 : 0);
1719 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1721 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1722 : 0);
1724 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1725 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1726 : 0);
1727 Vals.push_back(
1728 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1729
1730 Vals.push_back(F.isDSOLocal());
1731 Vals.push_back(F.getAddressSpace());
1732 Vals.push_back(addToStrtab(F.getPartition()));
1733 Vals.push_back(F.getPartition().size());
1734 Vals.push_back(getEncodedAlign(F.getPreferredAlignment()));
1735
1736 unsigned AbbrevToUse = 0;
1737 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1738 Vals.clear();
1739 }
1740
1741 // Emit the alias information.
1742 for (const GlobalAlias &A : M.aliases()) {
1743 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1744 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1745 // DSO_Local]
1746 Vals.push_back(addToStrtab(A.getName()));
1747 Vals.push_back(A.getName().size());
1748 Vals.push_back(VE.getTypeID(A.getValueType()));
1749 Vals.push_back(A.getType()->getAddressSpace());
1750 Vals.push_back(VE.getValueID(A.getAliasee()));
1756 Vals.push_back(A.isDSOLocal());
1757 Vals.push_back(addToStrtab(A.getPartition()));
1758 Vals.push_back(A.getPartition().size());
1759
1760 unsigned AbbrevToUse = 0;
1761 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1762 Vals.clear();
1763 }
1764
1765 // Emit the ifunc information.
1766 for (const GlobalIFunc &I : M.ifuncs()) {
1767 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1768 // val#, linkage, visibility, DSO_Local]
1769 Vals.push_back(addToStrtab(I.getName()));
1770 Vals.push_back(I.getName().size());
1771 Vals.push_back(VE.getTypeID(I.getValueType()));
1772 Vals.push_back(I.getType()->getAddressSpace());
1773 Vals.push_back(VE.getValueID(I.getResolver()));
1776 Vals.push_back(I.isDSOLocal());
1777 Vals.push_back(addToStrtab(I.getPartition()));
1778 Vals.push_back(I.getPartition().size());
1779 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1780 Vals.clear();
1781 }
1782
1783 writeValueSymbolTableForwardDecl();
1784}
1785
1787 uint64_t Flags = 0;
1788
1789 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1790 if (OBO->hasNoSignedWrap())
1791 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1792 if (OBO->hasNoUnsignedWrap())
1793 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1794 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1795 if (PEO->isExact())
1796 Flags |= 1 << bitc::PEO_EXACT;
1797 } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {
1798 if (PDI->isDisjoint())
1799 Flags |= 1 << bitc::PDI_DISJOINT;
1800 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1801 if (FPMO->hasAllowReassoc())
1802 Flags |= bitc::AllowReassoc;
1803 if (FPMO->hasNoNaNs())
1804 Flags |= bitc::NoNaNs;
1805 if (FPMO->hasNoInfs())
1806 Flags |= bitc::NoInfs;
1807 if (FPMO->hasNoSignedZeros())
1808 Flags |= bitc::NoSignedZeros;
1809 if (FPMO->hasAllowReciprocal())
1810 Flags |= bitc::AllowReciprocal;
1811 if (FPMO->hasAllowContract())
1812 Flags |= bitc::AllowContract;
1813 if (FPMO->hasApproxFunc())
1814 Flags |= bitc::ApproxFunc;
1815
1816 // Handle uitofp.
1817 if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1818 Flags <<= 1;
1819 if (NNI->hasNonNeg())
1820 Flags |= 1 << bitc::PNNI_NON_NEG;
1821 }
1822 } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1823 if (NNI->hasNonNeg())
1824 Flags |= 1 << bitc::PNNI_NON_NEG;
1825 } else if (const auto *TI = dyn_cast<TruncInst>(V)) {
1826 if (TI->hasNoSignedWrap())
1827 Flags |= 1 << bitc::TIO_NO_SIGNED_WRAP;
1828 if (TI->hasNoUnsignedWrap())
1829 Flags |= 1 << bitc::TIO_NO_UNSIGNED_WRAP;
1830 } else if (const auto *GEP = dyn_cast<GEPOperator>(V)) {
1831 if (GEP->isInBounds())
1832 Flags |= 1 << bitc::GEP_INBOUNDS;
1833 if (GEP->hasNoUnsignedSignedWrap())
1834 Flags |= 1 << bitc::GEP_NUSW;
1835 if (GEP->hasNoUnsignedWrap())
1836 Flags |= 1 << bitc::GEP_NUW;
1837 } else if (const auto *ICmp = dyn_cast<ICmpInst>(V)) {
1838 if (ICmp->hasSameSign())
1839 Flags |= 1 << bitc::ICMP_SAME_SIGN;
1840 }
1841
1842 return Flags;
1843}
1844
1845void ModuleBitcodeWriter::writeValueAsMetadata(
1846 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1847 // Mimic an MDNode with a value as one operand.
1848 Value *V = MD->getValue();
1849 Record.push_back(VE.getTypeID(V->getType()));
1850 Record.push_back(VE.getValueID(V));
1851 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1852 Record.clear();
1853}
1854
1855void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1856 SmallVectorImpl<uint64_t> &Record,
1857 unsigned Abbrev) {
1858 for (const MDOperand &MDO : N->operands()) {
1859 Metadata *MD = MDO;
1860 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1861 "Unexpected function-local metadata");
1862 Record.push_back(VE.getMetadataOrNullID(MD));
1863 }
1864 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1866 Record, Abbrev);
1867 Record.clear();
1868}
1869
1870unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1871 // Assume the column is usually under 128, and always output the inlined-at
1872 // location (it's never more expensive than building an array size 1).
1873 auto Abbv = std::make_shared<BitCodeAbbrev>();
1874 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1875 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isDistinct
1876 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // line
1877 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // column
1878 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // scope
1879 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // inlinedAt
1880 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isImplicitCode
1881 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // atomGroup
1882 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // atomRank
1883 return Stream.EmitAbbrev(std::move(Abbv));
1884}
1885
1886void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1887 SmallVectorImpl<uint64_t> &Record,
1888 unsigned &Abbrev) {
1889 if (!Abbrev)
1890 Abbrev = createDILocationAbbrev();
1891
1892 Record.push_back(N->isDistinct());
1893 Record.push_back(N->getLine());
1894 Record.push_back(N->getColumn());
1895 Record.push_back(VE.getMetadataID(N->getScope()));
1896 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1897 Record.push_back(N->isImplicitCode());
1898 Record.push_back(N->getAtomGroup());
1899 Record.push_back(N->getAtomRank());
1900 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1901 Record.clear();
1902}
1903
1904unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1905 // Assume the column is usually under 128, and always output the inlined-at
1906 // location (it's never more expensive than building an array size 1).
1907 auto Abbv = std::make_shared<BitCodeAbbrev>();
1908 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1909 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1910 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1911 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1912 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1913 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1914 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1915 return Stream.EmitAbbrev(std::move(Abbv));
1916}
1917
1918void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1919 SmallVectorImpl<uint64_t> &Record,
1920 unsigned &Abbrev) {
1921 if (!Abbrev)
1922 Abbrev = createGenericDINodeAbbrev();
1923
1924 Record.push_back(N->isDistinct());
1925 Record.push_back(N->getTag());
1926 Record.push_back(0); // Per-tag version field; unused for now.
1927
1928 for (auto &I : N->operands())
1929 Record.push_back(VE.getMetadataOrNullID(I));
1930
1931 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1932 Record.clear();
1933}
1934
1935void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1936 SmallVectorImpl<uint64_t> &Record,
1937 unsigned Abbrev) {
1938 const uint64_t Version = 2 << 1;
1939 Record.push_back((uint64_t)N->isDistinct() | Version);
1940 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1941 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1942 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1943 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1944
1945 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1946 Record.clear();
1947}
1948
1949void ModuleBitcodeWriter::writeDIGenericSubrange(
1950 const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record,
1951 unsigned Abbrev) {
1952 Record.push_back((uint64_t)N->isDistinct());
1953 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1954 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1955 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1956 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1957
1958 Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);
1959 Record.clear();
1960}
1961
1962void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1963 SmallVectorImpl<uint64_t> &Record,
1964 unsigned Abbrev) {
1965 const uint64_t IsBigInt = 1 << 2;
1966 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
1967 Record.push_back(N->getValue().getBitWidth());
1968 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1969 emitWideAPInt(Record, N->getValue());
1970
1971 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1972 Record.clear();
1973}
1974
1975void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1976 SmallVectorImpl<uint64_t> &Record,
1977 unsigned Abbrev) {
1978 const unsigned SizeIsMetadata = 0x2;
1979 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
1980 Record.push_back(N->getTag());
1981 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1982 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
1983 Record.push_back(N->getAlignInBits());
1984 Record.push_back(N->getEncoding());
1985 Record.push_back(N->getFlags());
1986 Record.push_back(N->getNumExtraInhabitants());
1987 Record.push_back(N->getDataSizeInBits());
1988 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1989 Record.push_back(N->getLine());
1990 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1991
1992 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1993 Record.clear();
1994}
1995
1996void ModuleBitcodeWriter::writeDIFixedPointType(
1997 const DIFixedPointType *N, SmallVectorImpl<uint64_t> &Record,
1998 unsigned Abbrev) {
1999 const unsigned SizeIsMetadata = 0x2;
2000 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2001 Record.push_back(N->getTag());
2002 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2003 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2004 Record.push_back(N->getAlignInBits());
2005 Record.push_back(N->getEncoding());
2006 Record.push_back(N->getFlags());
2007 Record.push_back(N->getKind());
2008 Record.push_back(N->getFactorRaw());
2009
2010 auto WriteWideInt = [&](const APInt &Value) {
2011 // Write an encoded word that holds the number of active words and
2012 // the number of bits.
2013 uint64_t NumWords = Value.getActiveWords();
2014 uint64_t Encoded = (NumWords << 32) | Value.getBitWidth();
2015 Record.push_back(Encoded);
2016 emitWideAPInt(Record, Value);
2017 };
2018
2019 WriteWideInt(N->getNumeratorRaw());
2020 WriteWideInt(N->getDenominatorRaw());
2021
2022 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2023 Record.push_back(N->getLine());
2024 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2025
2026 Stream.EmitRecord(bitc::METADATA_FIXED_POINT_TYPE, Record, Abbrev);
2027 Record.clear();
2028}
2029
2030void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
2031 SmallVectorImpl<uint64_t> &Record,
2032 unsigned Abbrev) {
2033 const unsigned SizeIsMetadata = 0x2;
2034 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2035 Record.push_back(N->getTag());
2036 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2037 Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
2038 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
2039 Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
2040 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2041 Record.push_back(N->getAlignInBits());
2042 Record.push_back(N->getEncoding());
2043
2044 Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
2045 Record.clear();
2046}
2047
2048void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
2049 SmallVectorImpl<uint64_t> &Record,
2050 unsigned Abbrev) {
2051 const unsigned SizeIsMetadata = 0x2;
2052 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2053 Record.push_back(N->getTag());
2054 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2055 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2056 Record.push_back(N->getLine());
2057 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2058 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2059 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2060 Record.push_back(N->getAlignInBits());
2061 Record.push_back(VE.getMetadataOrNullID(N->getRawOffsetInBits()));
2062 Record.push_back(N->getFlags());
2063 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
2064
2065 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
2066 // that there is no DWARF address space associated with DIDerivedType.
2067 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
2068 Record.push_back(*DWARFAddressSpace + 1);
2069 else
2070 Record.push_back(0);
2071
2072 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2073
2074 if (auto PtrAuthData = N->getPtrAuthData())
2075 Record.push_back(PtrAuthData->RawData);
2076 else
2077 Record.push_back(0);
2078
2079 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
2080 Record.clear();
2081}
2082
2083void ModuleBitcodeWriter::writeDISubrangeType(const DISubrangeType *N,
2084 SmallVectorImpl<uint64_t> &Record,
2085 unsigned Abbrev) {
2086 const unsigned SizeIsMetadata = 0x2;
2087 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2088 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2089 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2090 Record.push_back(N->getLine());
2091 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2092 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2093 Record.push_back(N->getAlignInBits());
2094 Record.push_back(N->getFlags());
2095 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2096 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
2097 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
2098 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
2099 Record.push_back(VE.getMetadataOrNullID(N->getRawBias()));
2100
2101 Stream.EmitRecord(bitc::METADATA_SUBRANGE_TYPE, Record, Abbrev);
2102 Record.clear();
2103}
2104
2105void ModuleBitcodeWriter::writeDICompositeType(
2106 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
2107 unsigned Abbrev) {
2108 const unsigned IsNotUsedInOldTypeRef = 0x2;
2109 const unsigned SizeIsMetadata = 0x4;
2110 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2111 (unsigned)N->isDistinct());
2112 Record.push_back(N->getTag());
2113 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2114 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2115 Record.push_back(N->getLine());
2116 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2117 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2118 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2119 Record.push_back(N->getAlignInBits());
2120 Record.push_back(VE.getMetadataOrNullID(N->getRawOffsetInBits()));
2121 Record.push_back(N->getFlags());
2122 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2123 Record.push_back(N->getRuntimeLang());
2124 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
2125 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2126 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
2127 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
2128 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
2129 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
2130 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
2131 Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
2132 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2133 Record.push_back(N->getNumExtraInhabitants());
2134 Record.push_back(VE.getMetadataOrNullID(N->getRawSpecification()));
2135 Record.push_back(
2136 N->getEnumKind().value_or(dwarf::DW_APPLE_ENUM_KIND_invalid));
2137 Record.push_back(VE.getMetadataOrNullID(N->getRawBitStride()));
2138
2139 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
2140 Record.clear();
2141}
2142
2143void ModuleBitcodeWriter::writeDISubroutineType(
2144 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
2145 unsigned Abbrev) {
2146 const unsigned HasNoOldTypeRefs = 0x2;
2147 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
2148 Record.push_back(N->getFlags());
2149 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
2150 Record.push_back(N->getCC());
2151
2152 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
2153 Record.clear();
2154}
2155
2156void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
2157 SmallVectorImpl<uint64_t> &Record,
2158 unsigned Abbrev) {
2159 Record.push_back(N->isDistinct());
2160 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
2161 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
2162 if (N->getRawChecksum()) {
2163 Record.push_back(N->getRawChecksum()->Kind);
2164 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
2165 } else {
2166 // Maintain backwards compatibility with the old internal representation of
2167 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
2168 Record.push_back(0);
2169 Record.push_back(VE.getMetadataOrNullID(nullptr));
2170 }
2171 auto Source = N->getRawSource();
2172 if (Source)
2173 Record.push_back(VE.getMetadataOrNullID(Source));
2174
2175 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
2176 Record.clear();
2177}
2178
2179void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
2180 SmallVectorImpl<uint64_t> &Record,
2181 unsigned Abbrev) {
2182 assert(N->isDistinct() && "Expected distinct compile units");
2183 Record.push_back(/* IsDistinct */ true);
2184
2185 auto Lang = N->getSourceLanguage();
2186 Record.push_back(Lang.getName());
2187 // Set bit so the MetadataLoader can distniguish between versioned and
2188 // unversioned names.
2189 if (Lang.hasVersionedName())
2190 Record.back() ^= (uint64_t(1) << 63);
2191
2192 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2193 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
2194 Record.push_back(N->isOptimized());
2195 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
2196 Record.push_back(N->getRuntimeVersion());
2197 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
2198 Record.push_back(N->getEmissionKind());
2199 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
2200 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
2201 Record.push_back(/* subprograms */ 0);
2202 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
2203 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
2204 Record.push_back(N->getDWOId());
2205 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
2206 Record.push_back(N->getSplitDebugInlining());
2207 Record.push_back(N->getDebugInfoForProfiling());
2208 Record.push_back((unsigned)N->getNameTableKind());
2209 Record.push_back(N->getRangesBaseAddress());
2210 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
2211 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
2212 Record.push_back(Lang.hasVersionedName() ? Lang.getVersion() : 0);
2213 Record.push_back(Lang.getDialect());
2214
2215 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
2216 Record.clear();
2217}
2218
2219void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
2220 SmallVectorImpl<uint64_t> &Record,
2221 unsigned Abbrev) {
2222 const uint64_t HasUnitFlag = 1 << 1;
2223 const uint64_t HasSPFlagsFlag = 1 << 2;
2224 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2225 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2226 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2227 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2228 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2229 Record.push_back(N->getLine());
2230 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2231 Record.push_back(N->getScopeLine());
2232 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
2233 Record.push_back(N->getSPFlags());
2234 Record.push_back(N->getVirtualIndex());
2235 Record.push_back(N->getFlags());
2236 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
2237 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2238 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
2239 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
2240 Record.push_back(N->getThisAdjustment());
2241 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
2242 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2243 Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
2244 Record.push_back(N->getKeyInstructionsEnabled());
2245
2246 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
2247 Record.clear();
2248}
2249
2250void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
2251 SmallVectorImpl<uint64_t> &Record,
2252 unsigned Abbrev) {
2253 Record.push_back(N->isDistinct());
2254 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2255 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2256 Record.push_back(N->getLine());
2257 Record.push_back(N->getColumn());
2258
2259 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
2260 Record.clear();
2261}
2262
2263void ModuleBitcodeWriter::writeDILexicalBlockFile(
2264 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
2265 unsigned Abbrev) {
2266 Record.push_back(N->isDistinct());
2267 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2268 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2269 Record.push_back(N->getDiscriminator());
2270
2271 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
2272 Record.clear();
2273}
2274
2275void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
2276 SmallVectorImpl<uint64_t> &Record,
2277 unsigned Abbrev) {
2278 Record.push_back(N->isDistinct());
2279 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2280 Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
2281 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2282 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2283 Record.push_back(N->getLineNo());
2284
2285 Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
2286 Record.clear();
2287}
2288
2289void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
2290 SmallVectorImpl<uint64_t> &Record,
2291 unsigned Abbrev) {
2292 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
2293 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2294 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2295
2296 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
2297 Record.clear();
2298}
2299
2300void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
2301 SmallVectorImpl<uint64_t> &Record,
2302 unsigned Abbrev) {
2303 Record.push_back(N->isDistinct());
2304 Record.push_back(N->getMacinfoType());
2305 Record.push_back(N->getLine());
2306 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2307 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
2308
2309 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
2310 Record.clear();
2311}
2312
2313void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
2314 SmallVectorImpl<uint64_t> &Record,
2315 unsigned Abbrev) {
2316 Record.push_back(N->isDistinct());
2317 Record.push_back(N->getMacinfoType());
2318 Record.push_back(N->getLine());
2319 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2320 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2321
2322 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
2323 Record.clear();
2324}
2325
2326void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
2327 SmallVectorImpl<uint64_t> &Record) {
2328 Record.reserve(N->getArgs().size());
2329 for (ValueAsMetadata *MD : N->getArgs())
2330 Record.push_back(VE.getMetadataID(MD));
2331
2332 Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record);
2333 Record.clear();
2334}
2335
2336void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
2337 SmallVectorImpl<uint64_t> &Record,
2338 unsigned Abbrev) {
2339 Record.push_back(N->isDistinct());
2340 for (auto &I : N->operands())
2341 Record.push_back(VE.getMetadataOrNullID(I));
2342 Record.push_back(N->getLineNo());
2343 Record.push_back(N->getIsDecl());
2344
2345 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
2346 Record.clear();
2347}
2348
2349void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
2350 SmallVectorImpl<uint64_t> &Record,
2351 unsigned Abbrev) {
2352 // There are no arguments for this metadata type.
2353 Record.push_back(N->isDistinct());
2354 Stream.EmitRecord(bitc::METADATA_ASSIGN_ID, Record, Abbrev);
2355 Record.clear();
2356}
2357
2358void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2359 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
2360 unsigned Abbrev) {
2361 Record.push_back(N->isDistinct());
2362 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2363 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2364 Record.push_back(N->isDefault());
2365
2366 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
2367 Record.clear();
2368}
2369
2370void ModuleBitcodeWriter::writeDITemplateValueParameter(
2371 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
2372 unsigned Abbrev) {
2373 Record.push_back(N->isDistinct());
2374 Record.push_back(N->getTag());
2375 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2376 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2377 Record.push_back(N->isDefault());
2378 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
2379
2380 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
2381 Record.clear();
2382}
2383
2384void ModuleBitcodeWriter::writeDIGlobalVariable(
2385 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
2386 unsigned Abbrev) {
2387 const uint64_t Version = 2 << 1;
2388 Record.push_back((uint64_t)N->isDistinct() | Version);
2389 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2390 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2391 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2392 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2393 Record.push_back(N->getLine());
2394 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2395 Record.push_back(N->isLocalToUnit());
2396 Record.push_back(N->isDefinition());
2397 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
2398 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
2399 Record.push_back(N->getAlignInBits());
2400 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2401
2402 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
2403 Record.clear();
2404}
2405
2406void ModuleBitcodeWriter::writeDILocalVariable(
2407 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
2408 unsigned Abbrev) {
2409 // In order to support all possible bitcode formats in BitcodeReader we need
2410 // to distinguish the following cases:
2411 // 1) Record has no artificial tag (Record[1]),
2412 // has no obsolete inlinedAt field (Record[9]).
2413 // In this case Record size will be 8, HasAlignment flag is false.
2414 // 2) Record has artificial tag (Record[1]),
2415 // has no obsolete inlignedAt field (Record[9]).
2416 // In this case Record size will be 9, HasAlignment flag is false.
2417 // 3) Record has both artificial tag (Record[1]) and
2418 // obsolete inlignedAt field (Record[9]).
2419 // In this case Record size will be 10, HasAlignment flag is false.
2420 // 4) Record has neither artificial tag, nor inlignedAt field, but
2421 // HasAlignment flag is true and Record[8] contains alignment value.
2422 const uint64_t HasAlignmentFlag = 1 << 1;
2423 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2424 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2425 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2426 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2427 Record.push_back(N->getLine());
2428 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2429 Record.push_back(N->getArg());
2430 Record.push_back(N->getFlags());
2431 Record.push_back(N->getAlignInBits());
2432 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2433
2434 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
2435 Record.clear();
2436}
2437
2438void ModuleBitcodeWriter::writeDILabel(
2439 const DILabel *N, SmallVectorImpl<uint64_t> &Record,
2440 unsigned Abbrev) {
2441 uint64_t IsArtificialFlag = uint64_t(N->isArtificial()) << 1;
2442 Record.push_back((uint64_t)N->isDistinct() | IsArtificialFlag);
2443 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2444 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2445 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2446 Record.push_back(N->getLine());
2447 Record.push_back(N->getColumn());
2448 Record.push_back(N->getCoroSuspendIdx().has_value()
2449 ? (uint64_t)N->getCoroSuspendIdx().value()
2450 : std::numeric_limits<uint64_t>::max());
2451
2452 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2453 Record.clear();
2454}
2455
2456void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
2457 SmallVectorImpl<uint64_t> &Record,
2458 unsigned Abbrev) {
2459 Record.reserve(N->getElements().size() + 1);
2460 const uint64_t Version = 3 << 1;
2461 Record.push_back((uint64_t)N->isDistinct() | Version);
2462 Record.append(N->elements_begin(), N->elements_end());
2463
2464 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
2465 Record.clear();
2466}
2467
2468void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2469 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
2470 unsigned Abbrev) {
2471 Record.push_back(N->isDistinct());
2472 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2473 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2474
2475 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
2476 Record.clear();
2477}
2478
2479void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
2480 SmallVectorImpl<uint64_t> &Record,
2481 unsigned Abbrev) {
2482 Record.push_back(N->isDistinct());
2483 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2484 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2485 Record.push_back(N->getLine());
2486 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2487 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2488 Record.push_back(N->getAttributes());
2489 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2490
2491 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
2492 Record.clear();
2493}
2494
2495void ModuleBitcodeWriter::writeDIImportedEntity(
2496 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
2497 unsigned Abbrev) {
2498 Record.push_back(N->isDistinct());
2499 Record.push_back(N->getTag());
2500 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2501 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2502 Record.push_back(N->getLine());
2503 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2504 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2505 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2506
2507 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
2508 Record.clear();
2509}
2510
2511unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2512 auto Abbv = std::make_shared<BitCodeAbbrev>();
2513 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
2514 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2515 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2516 return Stream.EmitAbbrev(std::move(Abbv));
2517}
2518
2519void ModuleBitcodeWriter::writeNamedMetadata(
2520 SmallVectorImpl<uint64_t> &Record) {
2521 if (M.named_metadata_empty())
2522 return;
2523
2524 unsigned Abbrev = createNamedMetadataAbbrev();
2525 for (const NamedMDNode &NMD : M.named_metadata()) {
2526 // Write name.
2527 StringRef Str = NMD.getName();
2528 Record.append(Str.bytes_begin(), Str.bytes_end());
2529 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2530 Record.clear();
2531
2532 // Write named metadata operands.
2533 for (const MDNode *N : NMD.operands())
2534 Record.push_back(VE.getMetadataID(N));
2535 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
2536 Record.clear();
2537 }
2538}
2539
2540unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2541 auto Abbv = std::make_shared<BitCodeAbbrev>();
2542 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
2543 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2544 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2545 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2546 return Stream.EmitAbbrev(std::move(Abbv));
2547}
2548
2549/// Write out a record for MDString.
2550///
2551/// All the metadata strings in a metadata block are emitted in a single
2552/// record. The sizes and strings themselves are shoved into a blob.
2553void ModuleBitcodeWriter::writeMetadataStrings(
2554 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
2555 if (Strings.empty())
2556 return;
2557
2558 // Start the record with the number of strings.
2559 Record.push_back(bitc::METADATA_STRINGS);
2560 Record.push_back(Strings.size());
2561
2562 // Emit the sizes of the strings in the blob.
2563 SmallString<256> Blob;
2564 {
2565 BitstreamWriter W(Blob);
2566 for (const Metadata *MD : Strings)
2567 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2568 W.FlushToWord();
2569 }
2570
2571 // Add the offset to the strings to the record.
2572 Record.push_back(Blob.size());
2573
2574 // Add the strings to the blob.
2575 for (const Metadata *MD : Strings)
2576 Blob.append(cast<MDString>(MD)->getString());
2577
2578 // Emit the final record.
2579 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2580 Record.clear();
2581}
2582
2583// Generates an enum to use as an index in the Abbrev array of Metadata record.
2584enum MetadataAbbrev : unsigned {
2585#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2586#include "llvm/IR/Metadata.def"
2588};
2589
2590void ModuleBitcodeWriter::writeMetadataRecords(
2591 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
2592 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2593 if (MDs.empty())
2594 return;
2595
2596 // Initialize MDNode abbreviations.
2597#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2598#include "llvm/IR/Metadata.def"
2599
2600 for (const Metadata *MD : MDs) {
2601 if (IndexPos)
2602 IndexPos->push_back(Stream.GetCurrentBitNo());
2603 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2604 assert(N->isResolved() && "Expected forward references to be resolved");
2605
2606 switch (N->getMetadataID()) {
2607 default:
2608 llvm_unreachable("Invalid MDNode subclass");
2609#define HANDLE_MDNODE_LEAF(CLASS) \
2610 case Metadata::CLASS##Kind: \
2611 if (MDAbbrevs) \
2612 write##CLASS(cast<CLASS>(N), Record, \
2613 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2614 else \
2615 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2616 continue;
2617#include "llvm/IR/Metadata.def"
2618 }
2619 }
2620 if (auto *AL = dyn_cast<DIArgList>(MD)) {
2622 continue;
2623 }
2624 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2625 }
2626}
2627
2628void ModuleBitcodeWriter::writeModuleMetadata() {
2629 if (!VE.hasMDs() && M.named_metadata_empty())
2630 return;
2631
2633 SmallVector<uint64_t, 64> Record;
2634
2635 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2636 // block and load any metadata.
2637 std::vector<unsigned> MDAbbrevs;
2638
2639 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2640 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2641 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2642 createGenericDINodeAbbrev();
2643
2644 auto Abbv = std::make_shared<BitCodeAbbrev>();
2645 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
2646 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2647 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2648 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2649
2650 Abbv = std::make_shared<BitCodeAbbrev>();
2651 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
2652 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2653 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2654 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2655
2656 // Emit MDStrings together upfront.
2657 writeMetadataStrings(VE.getMDStrings(), Record);
2658
2659 // We only emit an index for the metadata record if we have more than a given
2660 // (naive) threshold of metadatas, otherwise it is not worth it.
2661 if (VE.getNonMDStrings().size() > IndexThreshold) {
2662 // Write a placeholder value in for the offset of the metadata index,
2663 // which is written after the records, so that it can include
2664 // the offset of each entry. The placeholder offset will be
2665 // updated after all records are emitted.
2666 uint64_t Vals[] = {0, 0};
2667 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2668 }
2669
2670 // Compute and save the bit offset to the current position, which will be
2671 // patched when we emit the index later. We can simply subtract the 64-bit
2672 // fixed size from the current bit number to get the location to backpatch.
2673 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2674
2675 // This index will contain the bitpos for each individual record.
2676 std::vector<uint64_t> IndexPos;
2677 IndexPos.reserve(VE.getNonMDStrings().size());
2678
2679 // Write all the records
2680 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2681
2682 if (VE.getNonMDStrings().size() > IndexThreshold) {
2683 // Now that we have emitted all the records we will emit the index. But
2684 // first
2685 // backpatch the forward reference so that the reader can skip the records
2686 // efficiently.
2687 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2688 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2689
2690 // Delta encode the index.
2691 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2692 for (auto &Elt : IndexPos) {
2693 auto EltDelta = Elt - PreviousValue;
2694 PreviousValue = Elt;
2695 Elt = EltDelta;
2696 }
2697 // Emit the index record.
2698 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2699 IndexPos.clear();
2700 }
2701
2702 // Write the named metadata now.
2703 writeNamedMetadata(Record);
2704
2705 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2706 SmallVector<uint64_t, 4> Record;
2707 Record.push_back(VE.getValueID(&GO));
2708 pushGlobalMetadataAttachment(Record, GO);
2710 };
2711 for (const Function &F : M)
2712 if (F.isDeclaration() && F.hasMetadata())
2713 AddDeclAttachedMetadata(F);
2714 for (const GlobalIFunc &GI : M.ifuncs())
2715 if (GI.hasMetadata())
2716 AddDeclAttachedMetadata(GI);
2717 // FIXME: Only store metadata for declarations here, and move data for global
2718 // variable definitions to a separate block (PR28134).
2719 for (const GlobalVariable &GV : M.globals())
2720 if (GV.hasMetadata())
2721 AddDeclAttachedMetadata(GV);
2722
2723 Stream.ExitBlock();
2724}
2725
2726void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2727 if (!VE.hasMDs())
2728 return;
2729
2731 SmallVector<uint64_t, 64> Record;
2732 writeMetadataStrings(VE.getMDStrings(), Record);
2733 writeMetadataRecords(VE.getNonMDStrings(), Record);
2734 Stream.ExitBlock();
2735}
2736
2737void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2738 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2739 // [n x [id, mdnode]]
2741 GO.getAllMetadata(MDs);
2742 for (const auto &I : MDs) {
2743 Record.push_back(I.first);
2744 Record.push_back(VE.getMetadataID(I.second));
2745 }
2746}
2747
2748void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2750
2751 SmallVector<uint64_t, 64> Record;
2752
2753 if (F.hasMetadata()) {
2754 pushGlobalMetadataAttachment(Record, F);
2755 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2756 Record.clear();
2757 }
2758
2759 // Write metadata attachments
2760 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2762 for (const BasicBlock &BB : F)
2763 for (const Instruction &I : BB) {
2764 MDs.clear();
2765 I.getAllMetadataOtherThanDebugLoc(MDs);
2766
2767 // If no metadata, ignore instruction.
2768 if (MDs.empty()) continue;
2769
2770 Record.push_back(VE.getInstructionID(&I));
2771
2772 for (const auto &[ID, MD] : MDs) {
2773 Record.push_back(ID);
2774 Record.push_back(VE.getMetadataID(MD));
2775 }
2776 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2777 Record.clear();
2778 }
2779
2780 Stream.ExitBlock();
2781}
2782
2783void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2784 SmallVector<uint64_t, 64> Record;
2785
2786 // Write metadata kinds
2787 // METADATA_KIND - [n x [id, name]]
2789 M.getMDKindNames(Names);
2790
2791 if (Names.empty()) return;
2792
2794
2795 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2796 Record.push_back(MDKindID);
2797 StringRef KName = Names[MDKindID];
2798 Record.append(KName.begin(), KName.end());
2799
2800 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2801 Record.clear();
2802 }
2803
2804 Stream.ExitBlock();
2805}
2806
2807void ModuleBitcodeWriter::writeOperandBundleTags() {
2808 // Write metadata kinds
2809 //
2810 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2811 //
2812 // OPERAND_BUNDLE_TAG - [strchr x N]
2813
2815 M.getOperandBundleTags(Tags);
2816
2817 if (Tags.empty())
2818 return;
2819
2821
2822 SmallVector<uint64_t, 64> Record;
2823
2824 for (auto Tag : Tags) {
2825 Record.append(Tag.begin(), Tag.end());
2826
2827 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2828 Record.clear();
2829 }
2830
2831 Stream.ExitBlock();
2832}
2833
2834void ModuleBitcodeWriter::writeSyncScopeNames() {
2836 M.getContext().getSyncScopeNames(SSNs);
2837 if (SSNs.empty())
2838 return;
2839
2841
2842 SmallVector<uint64_t, 64> Record;
2843 for (auto SSN : SSNs) {
2844 Record.append(SSN.begin(), SSN.end());
2845 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2846 Record.clear();
2847 }
2848
2849 Stream.ExitBlock();
2850}
2851
2852void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2853 bool isGlobal) {
2854 if (FirstVal == LastVal) return;
2855
2857
2858 unsigned AggregateAbbrev = 0;
2859 unsigned String8Abbrev = 0;
2860 unsigned CString7Abbrev = 0;
2861 unsigned CString6Abbrev = 0;
2862 // If this is a constant pool for the module, emit module-specific abbrevs.
2863 if (isGlobal) {
2864 // Abbrev for CST_CODE_AGGREGATE.
2865 auto Abbv = std::make_shared<BitCodeAbbrev>();
2866 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2867 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2868 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2869 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2870
2871 // Abbrev for CST_CODE_STRING.
2872 Abbv = std::make_shared<BitCodeAbbrev>();
2873 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2874 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2875 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2876 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2877 // Abbrev for CST_CODE_CSTRING.
2878 Abbv = std::make_shared<BitCodeAbbrev>();
2879 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2880 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2881 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2882 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2883 // Abbrev for CST_CODE_CSTRING.
2884 Abbv = std::make_shared<BitCodeAbbrev>();
2885 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2886 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2887 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2888 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2889 }
2890
2891 SmallVector<uint64_t, 64> Record;
2892
2893 const ValueEnumerator::ValueList &Vals = VE.getValues();
2894 Type *LastTy = nullptr;
2895 for (unsigned i = FirstVal; i != LastVal; ++i) {
2896 const Value *V = Vals[i].first;
2897 // If we need to switch types, do so now.
2898 if (V->getType() != LastTy) {
2899 LastTy = V->getType();
2900 Record.push_back(VE.getTypeID(LastTy));
2901 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2902 CONSTANTS_SETTYPE_ABBREV);
2903 Record.clear();
2904 }
2905
2906 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2907 Record.push_back(VE.getTypeID(IA->getFunctionType()));
2908 Record.push_back(
2909 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2910 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2911
2912 // Add the asm string.
2913 StringRef AsmStr = IA->getAsmString();
2914 Record.push_back(AsmStr.size());
2915 Record.append(AsmStr.begin(), AsmStr.end());
2916
2917 // Add the constraint string.
2918 StringRef ConstraintStr = IA->getConstraintString();
2919 Record.push_back(ConstraintStr.size());
2920 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2921 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2922 Record.clear();
2923 continue;
2924 }
2925 const Constant *C = cast<Constant>(V);
2926 unsigned Code = -1U;
2927 unsigned AbbrevToUse = 0;
2928 if (C->isNullValue()) {
2930 } else if (isa<PoisonValue>(C)) {
2932 } else if (isa<UndefValue>(C)) {
2934 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2935 if (IV->getBitWidth() <= 64) {
2936 uint64_t V = IV->getSExtValue();
2937 emitSignedInt64(Record, V);
2939 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2940 } else { // Wide integers, > 64 bits in size.
2941 emitWideAPInt(Record, IV->getValue());
2943 }
2944 } else if (const ConstantByte *BV = dyn_cast<ConstantByte>(C)) {
2945 if (BV->getBitWidth() <= 64) {
2946 uint64_t V = BV->getSExtValue();
2947 emitSignedInt64(Record, V);
2949 AbbrevToUse = CONSTANTS_BYTE_ABBREV;
2950 } else { // Wide bytes, > 64 bits in size.
2951 emitWideAPInt(Record, BV->getValue());
2953 }
2954 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2956 Type *Ty = CFP->getType()->getScalarType();
2957 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2958 Ty->isDoubleTy()) {
2959 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2960 } else if (Ty->isX86_FP80Ty()) {
2961 // api needed to prevent premature destruction
2962 // bits are not in the same order as a normal i80 APInt, compensate.
2963 APInt api = CFP->getValueAPF().bitcastToAPInt();
2964 const uint64_t *p = api.getRawData();
2965 Record.push_back((p[1] << 48) | (p[0] >> 16));
2966 Record.push_back(p[0] & 0xffffLL);
2967 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2968 APInt api = CFP->getValueAPF().bitcastToAPInt();
2969 const uint64_t *p = api.getRawData();
2970 Record.push_back(p[0]);
2971 Record.push_back(p[1]);
2972 } else {
2973 assert(0 && "Unknown FP type!");
2974 }
2975 } else if (isa<ConstantDataSequential>(C) &&
2976 cast<ConstantDataSequential>(C)->isString()) {
2977 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2978 // Emit constant strings specially.
2979 uint64_t NumElts = Str->getNumElements();
2980 // If this is a null-terminated string, use the denser CSTRING encoding.
2981 if (Str->isCString()) {
2983 --NumElts; // Don't encode the null, which isn't allowed by char6.
2984 } else {
2986 AbbrevToUse = String8Abbrev;
2987 }
2988 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2989 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2990 for (uint64_t i = 0; i != NumElts; ++i) {
2991 unsigned char V = Str->getElementAsInteger(i);
2992 Record.push_back(V);
2993 isCStr7 &= (V & 128) == 0;
2994 if (isCStrChar6)
2995 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2996 }
2997
2998 if (isCStrChar6)
2999 AbbrevToUse = CString6Abbrev;
3000 else if (isCStr7)
3001 AbbrevToUse = CString7Abbrev;
3002 } else if (const ConstantDataSequential *CDS =
3005 Type *EltTy = CDS->getElementType();
3006 if (isa<IntegerType>(EltTy) || isa<ByteType>(EltTy)) {
3007 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3008 Record.push_back(CDS->getElementAsInteger(i));
3009 } else {
3010 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3011 Record.push_back(
3012 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
3013 }
3014 } else if (isa<ConstantAggregate>(C)) {
3016 for (const Value *Op : C->operands())
3017 Record.push_back(VE.getValueID(Op));
3018 AbbrevToUse = AggregateAbbrev;
3019 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
3020 switch (CE->getOpcode()) {
3021 default:
3022 if (Instruction::isCast(CE->getOpcode())) {
3024 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
3025 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3026 Record.push_back(VE.getValueID(C->getOperand(0)));
3027 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
3028 } else {
3029 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
3031 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
3032 Record.push_back(VE.getValueID(C->getOperand(0)));
3033 Record.push_back(VE.getValueID(C->getOperand(1)));
3034 uint64_t Flags = getOptimizationFlags(CE);
3035 if (Flags != 0)
3036 Record.push_back(Flags);
3037 }
3038 break;
3039 case Instruction::FNeg: {
3040 assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
3042 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
3043 Record.push_back(VE.getValueID(C->getOperand(0)));
3044 uint64_t Flags = getOptimizationFlags(CE);
3045 if (Flags != 0)
3046 Record.push_back(Flags);
3047 break;
3048 }
3049 case Instruction::GetElementPtr: {
3051 const auto *GO = cast<GEPOperator>(C);
3052 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
3053 Record.push_back(getOptimizationFlags(GO));
3054 if (std::optional<ConstantRange> Range = GO->getInRange()) {
3056 emitConstantRange(Record, *Range, /*EmitBitWidth=*/true);
3057 }
3058 for (const Value *Op : CE->operands()) {
3059 Record.push_back(VE.getTypeID(Op->getType()));
3060 Record.push_back(VE.getValueID(Op));
3061 }
3062 break;
3063 }
3064 case Instruction::ExtractElement:
3066 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3067 Record.push_back(VE.getValueID(C->getOperand(0)));
3068 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
3069 Record.push_back(VE.getValueID(C->getOperand(1)));
3070 break;
3071 case Instruction::InsertElement:
3073 Record.push_back(VE.getValueID(C->getOperand(0)));
3074 Record.push_back(VE.getValueID(C->getOperand(1)));
3075 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
3076 Record.push_back(VE.getValueID(C->getOperand(2)));
3077 break;
3078 case Instruction::ShuffleVector:
3079 // If the return type and argument types are the same, this is a
3080 // standard shufflevector instruction. If the types are different,
3081 // then the shuffle is widening or truncating the input vectors, and
3082 // the argument type must also be encoded.
3083 if (C->getType() == C->getOperand(0)->getType()) {
3085 } else {
3087 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3088 }
3089 Record.push_back(VE.getValueID(C->getOperand(0)));
3090 Record.push_back(VE.getValueID(C->getOperand(1)));
3091 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
3092 break;
3093 }
3094 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
3096 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
3097 Record.push_back(VE.getValueID(BA->getFunction()));
3098 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
3099 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
3101 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
3102 Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
3103 } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
3105 Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
3106 Record.push_back(VE.getValueID(NC->getGlobalValue()));
3107 } else if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C)) {
3109 Record.push_back(VE.getValueID(CPA->getPointer()));
3110 Record.push_back(VE.getValueID(CPA->getKey()));
3111 Record.push_back(VE.getValueID(CPA->getDiscriminator()));
3112 Record.push_back(VE.getValueID(CPA->getAddrDiscriminator()));
3113 Record.push_back(VE.getValueID(CPA->getDeactivationSymbol()));
3114 } else {
3115#ifndef NDEBUG
3116 C->dump();
3117#endif
3118 llvm_unreachable("Unknown constant!");
3119 }
3120 Stream.EmitRecord(Code, Record, AbbrevToUse);
3121 Record.clear();
3122 }
3123
3124 Stream.ExitBlock();
3125}
3126
3127void ModuleBitcodeWriter::writeModuleConstants() {
3128 const ValueEnumerator::ValueList &Vals = VE.getValues();
3129
3130 // Find the first constant to emit, which is the first non-globalvalue value.
3131 // We know globalvalues have been emitted by WriteModuleInfo.
3132 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
3133 if (!isa<GlobalValue>(Vals[i].first)) {
3134 writeConstants(i, Vals.size(), true);
3135 return;
3136 }
3137 }
3138}
3139
3140/// pushValueAndType - The file has to encode both the value and type id for
3141/// many values, because we need to know what type to create for forward
3142/// references. However, most operands are not forward references, so this type
3143/// field is not needed.
3144///
3145/// This function adds V's value ID to Vals. If the value ID is higher than the
3146/// instruction ID, then it is a forward reference, and it also includes the
3147/// type ID. The value ID that is written is encoded relative to the InstID.
3148bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
3149 SmallVectorImpl<unsigned> &Vals) {
3150 unsigned ValID = VE.getValueID(V);
3151 // Make encoding relative to the InstID.
3152 Vals.push_back(InstID - ValID);
3153 if (ValID >= InstID) {
3154 Vals.push_back(VE.getTypeID(V->getType()));
3155 return true;
3156 }
3157 return false;
3158}
3159
3160bool ModuleBitcodeWriter::pushValueOrMetadata(const Value *V, unsigned InstID,
3161 SmallVectorImpl<unsigned> &Vals) {
3162 bool IsMetadata = V->getType()->isMetadataTy();
3163 if (IsMetadata) {
3165 Metadata *MD = cast<MetadataAsValue>(V)->getMetadata();
3166 unsigned ValID = VE.getMetadataID(MD);
3167 Vals.push_back(InstID - ValID);
3168 return false;
3169 }
3170 return pushValueAndType(V, InstID, Vals);
3171}
3172
3173void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
3174 unsigned InstID) {
3176 LLVMContext &C = CS.getContext();
3177
3178 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
3179 const auto &Bundle = CS.getOperandBundleAt(i);
3180 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
3181
3182 for (auto &Input : Bundle.Inputs)
3183 pushValueOrMetadata(Input, InstID, Record);
3184
3186 Record.clear();
3187 }
3188}
3189
3190/// pushValue - Like pushValueAndType, but where the type of the value is
3191/// omitted (perhaps it was already encoded in an earlier operand).
3192void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
3193 SmallVectorImpl<unsigned> &Vals) {
3194 unsigned ValID = VE.getValueID(V);
3195 Vals.push_back(InstID - ValID);
3196}
3197
3198void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
3199 SmallVectorImpl<uint64_t> &Vals) {
3200 unsigned ValID = VE.getValueID(V);
3201 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3202 emitSignedInt64(Vals, diff);
3203}
3204
3205/// WriteInstruction - Emit an instruction to the specified stream.
3206void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
3207 unsigned InstID,
3208 SmallVectorImpl<unsigned> &Vals) {
3209 unsigned Code = 0;
3210 unsigned AbbrevToUse = 0;
3211 VE.setInstructionID(&I);
3212 switch (I.getOpcode()) {
3213 default:
3214 if (Instruction::isCast(I.getOpcode())) {
3216 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3217 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3218 Vals.push_back(VE.getTypeID(I.getType()));
3219 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
3220 uint64_t Flags = getOptimizationFlags(&I);
3221 if (Flags != 0) {
3222 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3223 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3224 Vals.push_back(Flags);
3225 }
3226 } else {
3227 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
3229 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3230 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3231 pushValue(I.getOperand(1), InstID, Vals);
3232 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
3233 uint64_t Flags = getOptimizationFlags(&I);
3234 if (Flags != 0) {
3235 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3236 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3237 Vals.push_back(Flags);
3238 }
3239 }
3240 break;
3241 case Instruction::FNeg: {
3243 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3244 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3245 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
3246 uint64_t Flags = getOptimizationFlags(&I);
3247 if (Flags != 0) {
3248 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3249 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3250 Vals.push_back(Flags);
3251 }
3252 break;
3253 }
3254 case Instruction::GetElementPtr: {
3256 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3257 auto &GEPInst = cast<GetElementPtrInst>(I);
3259 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
3260 for (const Value *Op : I.operands())
3261 pushValueAndType(Op, InstID, Vals);
3262 break;
3263 }
3264 case Instruction::ExtractValue: {
3266 pushValueAndType(I.getOperand(0), InstID, Vals);
3267 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3268 Vals.append(EVI->idx_begin(), EVI->idx_end());
3269 break;
3270 }
3271 case Instruction::InsertValue: {
3273 pushValueAndType(I.getOperand(0), InstID, Vals);
3274 pushValueAndType(I.getOperand(1), InstID, Vals);
3275 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
3276 Vals.append(IVI->idx_begin(), IVI->idx_end());
3277 break;
3278 }
3279 case Instruction::Select: {
3281 pushValueAndType(I.getOperand(1), InstID, Vals);
3282 pushValue(I.getOperand(2), InstID, Vals);
3283 pushValueAndType(I.getOperand(0), InstID, Vals);
3284 uint64_t Flags = getOptimizationFlags(&I);
3285 if (Flags != 0)
3286 Vals.push_back(Flags);
3287 break;
3288 }
3289 case Instruction::ExtractElement:
3291 pushValueAndType(I.getOperand(0), InstID, Vals);
3292 pushValueAndType(I.getOperand(1), InstID, Vals);
3293 break;
3294 case Instruction::InsertElement:
3296 pushValueAndType(I.getOperand(0), InstID, Vals);
3297 pushValue(I.getOperand(1), InstID, Vals);
3298 pushValueAndType(I.getOperand(2), InstID, Vals);
3299 break;
3300 case Instruction::ShuffleVector:
3302 pushValueAndType(I.getOperand(0), InstID, Vals);
3303 pushValue(I.getOperand(1), InstID, Vals);
3304 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
3305 Vals);
3306 break;
3307 case Instruction::ICmp:
3308 case Instruction::FCmp: {
3309 // compare returning Int1Ty or vector of Int1Ty
3311 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3312 if (pushValueAndType(I.getOperand(0), InstID, Vals))
3313 AbbrevToUse = 0;
3314 pushValue(I.getOperand(1), InstID, Vals);
3316 uint64_t Flags = getOptimizationFlags(&I);
3317 if (Flags != 0) {
3318 Vals.push_back(Flags);
3319 if (AbbrevToUse)
3320 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3321 }
3322 break;
3323 }
3324
3325 case Instruction::Ret:
3326 {
3328 unsigned NumOperands = I.getNumOperands();
3329 if (NumOperands == 0)
3330 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3331 else if (NumOperands == 1) {
3332 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3333 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3334 } else {
3335 for (const Value *Op : I.operands())
3336 pushValueAndType(Op, InstID, Vals);
3337 }
3338 }
3339 break;
3340 case Instruction::UncondBr: {
3342 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3343 const UncondBrInst &II = cast<UncondBrInst>(I);
3344 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3345 } break;
3346 case Instruction::CondBr: {
3348 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3349 const CondBrInst &II = cast<CondBrInst>(I);
3350 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3351 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
3352 pushValue(II.getCondition(), InstID, Vals);
3353 } break;
3354 case Instruction::Switch:
3355 {
3357 const SwitchInst &SI = cast<SwitchInst>(I);
3358 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
3359 pushValue(SI.getCondition(), InstID, Vals);
3360 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
3361 for (auto Case : SI.cases()) {
3362 Vals.push_back(VE.getValueID(Case.getCaseValue()));
3363 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
3364 }
3365 }
3366 break;
3367 case Instruction::IndirectBr:
3369 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3370 // Encode the address operand as relative, but not the basic blocks.
3371 pushValue(I.getOperand(0), InstID, Vals);
3372 for (const Value *Op : drop_begin(I.operands()))
3373 Vals.push_back(VE.getValueID(Op));
3374 break;
3375
3376 case Instruction::Invoke: {
3377 const InvokeInst *II = cast<InvokeInst>(&I);
3378 const Value *Callee = II->getCalledOperand();
3379 FunctionType *FTy = II->getFunctionType();
3380
3381 if (II->hasOperandBundles())
3382 writeOperandBundles(*II, InstID);
3383
3385
3386 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
3387 Vals.push_back(II->getCallingConv() | 1 << 13);
3388 Vals.push_back(VE.getValueID(II->getNormalDest()));
3389 Vals.push_back(VE.getValueID(II->getUnwindDest()));
3390 Vals.push_back(VE.getTypeID(FTy));
3391 pushValueAndType(Callee, InstID, Vals);
3392
3393 // Emit value #'s for the fixed parameters.
3394 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3395 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3396
3397 // Emit type/value pairs for varargs params.
3398 if (FTy->isVarArg()) {
3399 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
3400 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3401 }
3402 break;
3403 }
3404 case Instruction::Resume:
3406 pushValueAndType(I.getOperand(0), InstID, Vals);
3407 break;
3408 case Instruction::CleanupRet: {
3410 const auto &CRI = cast<CleanupReturnInst>(I);
3411 pushValue(CRI.getCleanupPad(), InstID, Vals);
3412 if (CRI.hasUnwindDest())
3413 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
3414 break;
3415 }
3416 case Instruction::CatchRet: {
3418 const auto &CRI = cast<CatchReturnInst>(I);
3419 pushValue(CRI.getCatchPad(), InstID, Vals);
3420 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
3421 break;
3422 }
3423 case Instruction::CleanupPad:
3424 case Instruction::CatchPad: {
3425 const auto &FuncletPad = cast<FuncletPadInst>(I);
3428 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3429
3430 unsigned NumArgOperands = FuncletPad.arg_size();
3431 Vals.push_back(NumArgOperands);
3432 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
3433 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
3434 break;
3435 }
3436 case Instruction::CatchSwitch: {
3438 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
3439
3440 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3441
3442 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3443 Vals.push_back(NumHandlers);
3444 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3445 Vals.push_back(VE.getValueID(CatchPadBB));
3446
3447 if (CatchSwitch.hasUnwindDest())
3448 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3449 break;
3450 }
3451 case Instruction::CallBr: {
3452 const CallBrInst *CBI = cast<CallBrInst>(&I);
3453 const Value *Callee = CBI->getCalledOperand();
3454 FunctionType *FTy = CBI->getFunctionType();
3455
3456 if (CBI->hasOperandBundles())
3457 writeOperandBundles(*CBI, InstID);
3458
3460
3462
3465
3466 Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3467 Vals.push_back(CBI->getNumIndirectDests());
3468 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3469 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3470
3471 Vals.push_back(VE.getTypeID(FTy));
3472 pushValueAndType(Callee, InstID, Vals);
3473
3474 // Emit value #'s for the fixed parameters.
3475 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3476 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3477
3478 // Emit type/value pairs for varargs params.
3479 if (FTy->isVarArg()) {
3480 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3481 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3482 }
3483 break;
3484 }
3485 case Instruction::Unreachable:
3487 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3488 break;
3489
3490 case Instruction::PHI: {
3491 const PHINode &PN = cast<PHINode>(I);
3493 // With the newer instruction encoding, forward references could give
3494 // negative valued IDs. This is most common for PHIs, so we use
3495 // signed VBRs.
3497 Vals64.push_back(VE.getTypeID(PN.getType()));
3498 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3499 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3500 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3501 }
3502
3503 uint64_t Flags = getOptimizationFlags(&I);
3504 if (Flags != 0)
3505 Vals64.push_back(Flags);
3506
3507 // Emit a Vals64 vector and exit.
3508 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3509 Vals64.clear();
3510 return;
3511 }
3512
3513 case Instruction::LandingPad: {
3514 const LandingPadInst &LP = cast<LandingPadInst>(I);
3516 Vals.push_back(VE.getTypeID(LP.getType()));
3517 Vals.push_back(LP.isCleanup());
3518 Vals.push_back(LP.getNumClauses());
3519 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3520 if (LP.isCatch(I))
3522 else
3524 pushValueAndType(LP.getClause(I), InstID, Vals);
3525 }
3526 break;
3527 }
3528
3529 case Instruction::Alloca: {
3531 const AllocaInst &AI = cast<AllocaInst>(I);
3532 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3533 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3534 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3535 using APV = AllocaPackedValues;
3536 unsigned Record = 0;
3537 unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3539 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3541 EncodedAlign >> APV::AlignLower::Bits);
3545 Vals.push_back(Record);
3546
3547 unsigned AS = AI.getAddressSpace();
3548 if (AS != M.getDataLayout().getAllocaAddrSpace())
3549 Vals.push_back(AS);
3550 break;
3551 }
3552
3553 case Instruction::Load:
3554 if (cast<LoadInst>(I).isAtomic()) {
3556 pushValueAndType(I.getOperand(0), InstID, Vals);
3557 } else {
3559 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3560 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3561 }
3562 Vals.push_back(VE.getTypeID(I.getType()));
3563 Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3564 Vals.push_back(cast<LoadInst>(I).isVolatile());
3565 if (cast<LoadInst>(I).isAtomic()) {
3566 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3567 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3568 }
3569 break;
3570 case Instruction::Store:
3571 if (cast<StoreInst>(I).isAtomic()) {
3573 } else {
3575 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3576 }
3577 if (pushValueAndType(I.getOperand(1), InstID, Vals)) // ptrty + ptr
3578 AbbrevToUse = 0;
3579 if (pushValueAndType(I.getOperand(0), InstID, Vals)) // valty + val
3580 AbbrevToUse = 0;
3581 Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3582 Vals.push_back(cast<StoreInst>(I).isVolatile());
3583 if (cast<StoreInst>(I).isAtomic()) {
3584 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3585 Vals.push_back(
3586 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3587 }
3588 break;
3589 case Instruction::AtomicCmpXchg:
3591 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3592 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3593 pushValue(I.getOperand(2), InstID, Vals); // newval.
3594 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3595 Vals.push_back(
3596 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3597 Vals.push_back(
3598 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3599 Vals.push_back(
3600 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3601 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3602 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3603 break;
3604 case Instruction::AtomicRMW:
3606 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3607 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3609 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3610 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3611 Vals.push_back(
3612 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3613 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3614 break;
3615 case Instruction::Fence:
3617 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3618 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3619 break;
3620 case Instruction::Call: {
3621 const CallInst &CI = cast<CallInst>(I);
3622 FunctionType *FTy = CI.getFunctionType();
3623
3624 if (CI.hasOperandBundles())
3625 writeOperandBundles(CI, InstID);
3626
3628
3630
3631 unsigned Flags = getOptimizationFlags(&I);
3633 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3634 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3636 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3637 unsigned(Flags != 0) << bitc::CALL_FMF);
3638 if (Flags != 0)
3639 Vals.push_back(Flags);
3640
3641 Vals.push_back(VE.getTypeID(FTy));
3642 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3643
3644 // Emit value #'s for the fixed parameters.
3645 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3646 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3647
3648 // Emit type/value pairs for varargs params.
3649 if (FTy->isVarArg()) {
3650 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3651 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3652 }
3653 break;
3654 }
3655 case Instruction::VAArg:
3657 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3658 pushValue(I.getOperand(0), InstID, Vals); // valist.
3659 Vals.push_back(VE.getTypeID(I.getType())); // restype.
3660 break;
3661 case Instruction::Freeze:
3663 pushValueAndType(I.getOperand(0), InstID, Vals);
3664 break;
3665 }
3666
3667 Stream.EmitRecord(Code, Vals, AbbrevToUse);
3668 Vals.clear();
3669}
3670
3671/// Write a GlobalValue VST to the module. The purpose of this data structure is
3672/// to allow clients to efficiently find the function body.
3673void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3674 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3675 // Get the offset of the VST we are writing, and backpatch it into
3676 // the VST forward declaration record.
3677 uint64_t VSTOffset = Stream.GetCurrentBitNo();
3678 // The BitcodeStartBit was the stream offset of the identification block.
3679 VSTOffset -= bitcodeStartBit();
3680 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3681 // Note that we add 1 here because the offset is relative to one word
3682 // before the start of the identification block, which was historically
3683 // always the start of the regular bitcode header.
3684 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3685
3687
3688 auto Abbv = std::make_shared<BitCodeAbbrev>();
3689 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
3690 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3691 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3692 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3693
3694 for (const Function &F : M) {
3695 uint64_t Record[2];
3696
3697 if (F.isDeclaration())
3698 continue;
3699
3700 Record[0] = VE.getValueID(&F);
3701
3702 // Save the word offset of the function (from the start of the
3703 // actual bitcode written to the stream).
3704 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3705 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3706 // Note that we add 1 here because the offset is relative to one word
3707 // before the start of the identification block, which was historically
3708 // always the start of the regular bitcode header.
3709 Record[1] = BitcodeIndex / 32 + 1;
3710
3711 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3712 }
3713
3714 Stream.ExitBlock();
3715}
3716
3717/// Emit names for arguments, instructions and basic blocks in a function.
3718void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3719 const ValueSymbolTable &VST) {
3720 if (VST.empty())
3721 return;
3722
3724
3725 // FIXME: Set up the abbrev, we know how many values there are!
3726 // FIXME: We know if the type names can use 7-bit ascii.
3727 SmallVector<uint64_t, 64> NameVals;
3728
3729 for (const ValueName &Name : VST) {
3730 // Figure out the encoding to use for the name.
3732
3733 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3734 NameVals.push_back(VE.getValueID(Name.getValue()));
3735
3736 // VST_CODE_ENTRY: [valueid, namechar x N]
3737 // VST_CODE_BBENTRY: [bbid, namechar x N]
3738 unsigned Code;
3739 if (isa<BasicBlock>(Name.getValue())) {
3741 if (Bits == SE_Char6)
3742 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3743 } else {
3745 if (Bits == SE_Char6)
3746 AbbrevToUse = VST_ENTRY_6_ABBREV;
3747 else if (Bits == SE_Fixed7)
3748 AbbrevToUse = VST_ENTRY_7_ABBREV;
3749 }
3750
3751 for (const auto P : Name.getKey())
3752 NameVals.push_back((unsigned char)P);
3753
3754 // Emit the finished record.
3755 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3756 NameVals.clear();
3757 }
3758
3759 Stream.ExitBlock();
3760}
3761
3762void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3763 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3764 unsigned Code;
3765 if (isa<BasicBlock>(Order.V))
3767 else
3769
3770 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3771 Record.push_back(VE.getValueID(Order.V));
3772 Stream.EmitRecord(Code, Record);
3773}
3774
3775void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3777 "Expected to be preserving use-list order");
3778
3779 auto hasMore = [&]() {
3780 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3781 };
3782 if (!hasMore())
3783 // Nothing to do.
3784 return;
3785
3787 while (hasMore()) {
3788 writeUseList(std::move(VE.UseListOrders.back()));
3789 VE.UseListOrders.pop_back();
3790 }
3791 Stream.ExitBlock();
3792}
3793
3794/// Emit a function body to the module stream.
3795void ModuleBitcodeWriter::writeFunction(
3796 const Function &F,
3797 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3798 // Save the bitcode index of the start of this function block for recording
3799 // in the VST.
3800 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3801
3804
3806
3807 // Emit the number of basic blocks, so the reader can create them ahead of
3808 // time.
3809 Vals.push_back(VE.getBasicBlocks().size());
3811 Vals.clear();
3812
3813 // If there are function-local constants, emit them now.
3814 unsigned CstStart, CstEnd;
3815 VE.getFunctionConstantRange(CstStart, CstEnd);
3816 writeConstants(CstStart, CstEnd, false);
3817
3818 // If there is function-local metadata, emit it now.
3819 writeFunctionMetadata(F);
3820
3821 // Keep a running idea of what the instruction ID is.
3822 unsigned InstID = CstEnd;
3823
3824 bool NeedsMetadataAttachment = F.hasMetadata();
3825
3826 DILocation *LastDL = nullptr;
3827 SmallSetVector<Function *, 4> BlockAddressUsers;
3828
3829 // Finally, emit all the instructions, in order.
3830 for (const BasicBlock &BB : F) {
3831 for (const Instruction &I : BB) {
3832 writeInstruction(I, InstID, Vals);
3833
3834 if (!I.getType()->isVoidTy())
3835 ++InstID;
3836
3837 // If the instruction has metadata, write a metadata attachment later.
3838 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3839
3840 // If the instruction has a debug location, emit it.
3841 if (DILocation *DL = I.getDebugLoc()) {
3842 if (DL == LastDL) {
3843 // Just repeat the same debug loc as last time.
3845 } else {
3846 Vals.push_back(DL->getLine());
3847 Vals.push_back(DL->getColumn());
3848 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3849 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3850 Vals.push_back(DL->isImplicitCode());
3851 Vals.push_back(DL->getAtomGroup());
3852 Vals.push_back(DL->getAtomRank());
3854 FUNCTION_DEBUG_LOC_ABBREV);
3855 Vals.clear();
3856 LastDL = DL;
3857 }
3858 }
3859
3860 // If the instruction has DbgRecords attached to it, emit them. Note that
3861 // they come after the instruction so that it's easy to attach them again
3862 // when reading the bitcode, even though conceptually the debug locations
3863 // start "before" the instruction.
3864 if (I.hasDbgRecords()) {
3865 /// Try to push the value only (unwrapped), otherwise push the
3866 /// metadata wrapped value. Returns true if the value was pushed
3867 /// without the ValueAsMetadata wrapper.
3868 auto PushValueOrMetadata = [&Vals, InstID,
3869 this](Metadata *RawLocation) {
3870 assert(RawLocation &&
3871 "RawLocation unexpectedly null in DbgVariableRecord");
3872 if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) {
3873 SmallVector<unsigned, 2> ValAndType;
3874 // If the value is a fwd-ref the type is also pushed. We don't
3875 // want the type, so fwd-refs are kept wrapped (pushValueAndType
3876 // returns false if the value is pushed without type).
3877 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
3878 Vals.push_back(ValAndType[0]);
3879 return true;
3880 }
3881 }
3882 // The metadata is a DIArgList, or ValueAsMetadata wrapping a
3883 // fwd-ref. Push the metadata ID.
3884 Vals.push_back(VE.getMetadataID(RawLocation));
3885 return false;
3886 };
3887
3888 // Write out non-instruction debug information attached to this
3889 // instruction. Write it after the instruction so that it's easy to
3890 // re-attach to the instruction reading the records in.
3891 for (DbgRecord &DR : I.DebugMarker->getDbgRecordRange()) {
3892 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
3893 Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc()));
3894 Vals.push_back(VE.getMetadataID(DLR->getLabel()));
3896 Vals.clear();
3897 continue;
3898 }
3899
3900 // First 3 fields are common to all kinds:
3901 // DILocation, DILocalVariable, DIExpression
3902 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
3903 // ..., LocationMetadata
3904 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
3905 // ..., Value
3906 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
3907 // ..., LocationMetadata
3908 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
3909 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
3910 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
3911 Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc()));
3912 Vals.push_back(VE.getMetadataID(DVR.getVariable()));
3913 Vals.push_back(VE.getMetadataID(DVR.getExpression()));
3914 if (DVR.isDbgValue()) {
3915 if (PushValueOrMetadata(DVR.getRawLocation()))
3917 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
3918 else
3920 } else if (DVR.isDbgDeclare()) {
3921 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3923 } else if (DVR.isDbgDeclareValue()) {
3924 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3926 } else {
3927 assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind");
3928 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3929 Vals.push_back(VE.getMetadataID(DVR.getAssignID()));
3931 Vals.push_back(VE.getMetadataID(DVR.getRawAddress()));
3933 }
3934 Vals.clear();
3935 }
3936 }
3937 }
3938
3939 if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
3940 SmallVector<Value *> Worklist{BA};
3941 SmallPtrSet<Value *, 8> Visited{BA};
3942 while (!Worklist.empty()) {
3943 Value *V = Worklist.pop_back_val();
3944 for (User *U : V->users()) {
3945 if (auto *I = dyn_cast<Instruction>(U)) {
3946 Function *P = I->getFunction();
3947 if (P != &F)
3948 BlockAddressUsers.insert(P);
3949 } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
3950 Visited.insert(U).second)
3951 Worklist.push_back(U);
3952 }
3953 }
3954 }
3955 }
3956
3957 if (!BlockAddressUsers.empty()) {
3958 Vals.resize(BlockAddressUsers.size());
3959 for (auto I : llvm::enumerate(BlockAddressUsers))
3960 Vals[I.index()] = VE.getValueID(I.value());
3962 Vals.clear();
3963 }
3964
3965 // Emit names for all the instructions etc.
3966 if (auto *Symtab = F.getValueSymbolTable())
3967 writeFunctionLevelValueSymbolTable(*Symtab);
3968
3969 if (NeedsMetadataAttachment)
3970 writeFunctionMetadataAttachment(F);
3972 writeUseListBlock(&F);
3973 VE.purgeFunction();
3974 Stream.ExitBlock();
3975}
3976
3977// Emit blockinfo, which defines the standard abbreviations etc.
3978void ModuleBitcodeWriter::writeBlockInfo() {
3979 // We only want to emit block info records for blocks that have multiple
3980 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3981 // Other blocks can define their abbrevs inline.
3982 Stream.EnterBlockInfoBlock();
3983
3984 // Encode type indices using fixed size based on number of types.
3985 BitCodeAbbrevOp TypeAbbrevOp(BitCodeAbbrevOp::Fixed,
3987 // Encode value indices as 6-bit VBR.
3988 BitCodeAbbrevOp ValAbbrevOp(BitCodeAbbrevOp::VBR, 6);
3989
3990 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3991 auto Abbv = std::make_shared<BitCodeAbbrev>();
3992 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3993 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3994 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3995 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3997 VST_ENTRY_8_ABBREV)
3998 llvm_unreachable("Unexpected abbrev ordering!");
3999 }
4000
4001 { // 7-bit fixed width VST_CODE_ENTRY strings.
4002 auto Abbv = std::make_shared<BitCodeAbbrev>();
4003 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
4004 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4005 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4006 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
4008 VST_ENTRY_7_ABBREV)
4009 llvm_unreachable("Unexpected abbrev ordering!");
4010 }
4011 { // 6-bit char6 VST_CODE_ENTRY strings.
4012 auto Abbv = std::make_shared<BitCodeAbbrev>();
4013 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
4014 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4015 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4016 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4018 VST_ENTRY_6_ABBREV)
4019 llvm_unreachable("Unexpected abbrev ordering!");
4020 }
4021 { // 6-bit char6 VST_CODE_BBENTRY strings.
4022 auto Abbv = std::make_shared<BitCodeAbbrev>();
4023 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
4024 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4025 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4026 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4028 VST_BBENTRY_6_ABBREV)
4029 llvm_unreachable("Unexpected abbrev ordering!");
4030 }
4031
4032 { // SETTYPE abbrev for CONSTANTS_BLOCK.
4033 auto Abbv = std::make_shared<BitCodeAbbrev>();
4034 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
4035 Abbv->Add(TypeAbbrevOp);
4037 CONSTANTS_SETTYPE_ABBREV)
4038 llvm_unreachable("Unexpected abbrev ordering!");
4039 }
4040
4041 { // INTEGER abbrev for CONSTANTS_BLOCK.
4042 auto Abbv = std::make_shared<BitCodeAbbrev>();
4043 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
4044 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4046 CONSTANTS_INTEGER_ABBREV)
4047 llvm_unreachable("Unexpected abbrev ordering!");
4048 }
4049
4050 { // BYTE abbrev for CONSTANTS_BLOCK.
4051 auto Abbv = std::make_shared<BitCodeAbbrev>();
4052 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_BYTE));
4053 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4055 CONSTANTS_BYTE_ABBREV)
4056 llvm_unreachable("Unexpected abbrev ordering!");
4057 }
4058
4059 { // CE_CAST abbrev for CONSTANTS_BLOCK.
4060 auto Abbv = std::make_shared<BitCodeAbbrev>();
4061 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
4062 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
4063 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
4065 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
4066
4068 CONSTANTS_CE_CAST_Abbrev)
4069 llvm_unreachable("Unexpected abbrev ordering!");
4070 }
4071 { // NULL abbrev for CONSTANTS_BLOCK.
4072 auto Abbv = std::make_shared<BitCodeAbbrev>();
4073 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
4075 CONSTANTS_NULL_Abbrev)
4076 llvm_unreachable("Unexpected abbrev ordering!");
4077 }
4078
4079 // FIXME: This should only use space for first class types!
4080
4081 { // INST_LOAD abbrev for FUNCTION_BLOCK.
4082 auto Abbv = std::make_shared<BitCodeAbbrev>();
4083 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
4084 Abbv->Add(ValAbbrevOp); // Ptr
4085 Abbv->Add(TypeAbbrevOp); // dest ty
4086 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
4087 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
4088 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4089 FUNCTION_INST_LOAD_ABBREV)
4090 llvm_unreachable("Unexpected abbrev ordering!");
4091 }
4092 {
4093 auto Abbv = std::make_shared<BitCodeAbbrev>();
4094 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_STORE));
4095 Abbv->Add(ValAbbrevOp); // op1
4096 Abbv->Add(ValAbbrevOp); // op0
4097 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // align
4098 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
4099 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4100 FUNCTION_INST_STORE_ABBREV)
4101 llvm_unreachable("Unexpected abbrev ordering!");
4102 }
4103 { // INST_UNOP abbrev for FUNCTION_BLOCK.
4104 auto Abbv = std::make_shared<BitCodeAbbrev>();
4105 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
4106 Abbv->Add(ValAbbrevOp); // LHS
4107 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4108 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4109 FUNCTION_INST_UNOP_ABBREV)
4110 llvm_unreachable("Unexpected abbrev ordering!");
4111 }
4112 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
4113 auto Abbv = std::make_shared<BitCodeAbbrev>();
4114 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
4115 Abbv->Add(ValAbbrevOp); // LHS
4116 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4117 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4118 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4119 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4120 llvm_unreachable("Unexpected abbrev ordering!");
4121 }
4122 { // INST_BINOP abbrev for FUNCTION_BLOCK.
4123 auto Abbv = std::make_shared<BitCodeAbbrev>();
4124 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
4125 Abbv->Add(ValAbbrevOp); // LHS
4126 Abbv->Add(ValAbbrevOp); // RHS
4127 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4128 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4129 FUNCTION_INST_BINOP_ABBREV)
4130 llvm_unreachable("Unexpected abbrev ordering!");
4131 }
4132 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
4133 auto Abbv = std::make_shared<BitCodeAbbrev>();
4134 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
4135 Abbv->Add(ValAbbrevOp); // LHS
4136 Abbv->Add(ValAbbrevOp); // RHS
4137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4139 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4140 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4141 llvm_unreachable("Unexpected abbrev ordering!");
4142 }
4143 { // INST_CAST abbrev for FUNCTION_BLOCK.
4144 auto Abbv = std::make_shared<BitCodeAbbrev>();
4145 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
4146 Abbv->Add(ValAbbrevOp); // OpVal
4147 Abbv->Add(TypeAbbrevOp); // dest ty
4148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4149 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4150 FUNCTION_INST_CAST_ABBREV)
4151 llvm_unreachable("Unexpected abbrev ordering!");
4152 }
4153 { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
4154 auto Abbv = std::make_shared<BitCodeAbbrev>();
4155 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
4156 Abbv->Add(ValAbbrevOp); // OpVal
4157 Abbv->Add(TypeAbbrevOp); // dest ty
4158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 9)); // flags
4160 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4161 FUNCTION_INST_CAST_FLAGS_ABBREV)
4162 llvm_unreachable("Unexpected abbrev ordering!");
4163 }
4164
4165 { // INST_RET abbrev for FUNCTION_BLOCK.
4166 auto Abbv = std::make_shared<BitCodeAbbrev>();
4167 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
4168 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4169 FUNCTION_INST_RET_VOID_ABBREV)
4170 llvm_unreachable("Unexpected abbrev ordering!");
4171 }
4172 { // INST_RET abbrev for FUNCTION_BLOCK.
4173 auto Abbv = std::make_shared<BitCodeAbbrev>();
4174 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
4175 Abbv->Add(ValAbbrevOp);
4176 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4177 FUNCTION_INST_RET_VAL_ABBREV)
4178 llvm_unreachable("Unexpected abbrev ordering!");
4179 }
4180 {
4181 auto Abbv = std::make_shared<BitCodeAbbrev>();
4182 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BR));
4183 // TODO: Use different abbrev for absolute value reference (succ0)?
4184 Abbv->Add(ValAbbrevOp); // succ0
4185 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4186 FUNCTION_INST_BR_UNCOND_ABBREV)
4187 llvm_unreachable("Unexpected abbrev ordering!");
4188 }
4189 {
4190 auto Abbv = std::make_shared<BitCodeAbbrev>();
4191 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BR));
4192 // TODO: Use different abbrev for absolute value references (succ0, succ1)?
4193 Abbv->Add(ValAbbrevOp); // succ0
4194 Abbv->Add(ValAbbrevOp); // succ1
4195 Abbv->Add(ValAbbrevOp); // cond
4196 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4197 FUNCTION_INST_BR_COND_ABBREV)
4198 llvm_unreachable("Unexpected abbrev ordering!");
4199 }
4200 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
4201 auto Abbv = std::make_shared<BitCodeAbbrev>();
4202 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
4203 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4204 FUNCTION_INST_UNREACHABLE_ABBREV)
4205 llvm_unreachable("Unexpected abbrev ordering!");
4206 }
4207 {
4208 auto Abbv = std::make_shared<BitCodeAbbrev>();
4209 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
4210 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // flags
4211 Abbv->Add(TypeAbbrevOp); // dest ty
4212 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4213 Abbv->Add(ValAbbrevOp);
4214 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4215 FUNCTION_INST_GEP_ABBREV)
4216 llvm_unreachable("Unexpected abbrev ordering!");
4217 }
4218 {
4219 auto Abbv = std::make_shared<BitCodeAbbrev>();
4220 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CMP2));
4221 Abbv->Add(ValAbbrevOp); // op0
4222 Abbv->Add(ValAbbrevOp); // op1
4223 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 6)); // pred
4224 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4225 FUNCTION_INST_CMP_ABBREV)
4226 llvm_unreachable("Unexpected abbrev ordering!");
4227 }
4228 {
4229 auto Abbv = std::make_shared<BitCodeAbbrev>();
4230 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CMP2));
4231 Abbv->Add(ValAbbrevOp); // op0
4232 Abbv->Add(ValAbbrevOp); // op1
4233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 6)); // pred
4234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4235 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4236 FUNCTION_INST_CMP_FLAGS_ABBREV)
4237 llvm_unreachable("Unexpected abbrev ordering!");
4238 }
4239 {
4240 auto Abbv = std::make_shared<BitCodeAbbrev>();
4241 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE));
4242 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc
4243 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var
4244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr
4245 Abbv->Add(ValAbbrevOp); // val
4246 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4247 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4248 llvm_unreachable("Unexpected abbrev ordering! 1");
4249 }
4250 {
4251 auto Abbv = std::make_shared<BitCodeAbbrev>();
4252 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_LOC));
4253 // NOTE: No IsDistinct field for FUNC_CODE_DEBUG_LOC.
4254 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4255 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4256 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4257 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
4259 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Atom group.
4260 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Atom rank.
4261 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4262 FUNCTION_DEBUG_LOC_ABBREV)
4263 llvm_unreachable("Unexpected abbrev ordering!");
4264 }
4265 Stream.ExitBlock();
4266}
4267
4268/// Write the module path strings, currently only used when generating
4269/// a combined index file.
4270void IndexBitcodeWriter::writeModStrings() {
4272
4273 // TODO: See which abbrev sizes we actually need to emit
4274
4275 // 8-bit fixed-width MST_ENTRY strings.
4276 auto Abbv = std::make_shared<BitCodeAbbrev>();
4277 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4278 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4279 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4280 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
4281 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
4282
4283 // 7-bit fixed width MST_ENTRY strings.
4284 Abbv = std::make_shared<BitCodeAbbrev>();
4285 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4286 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4287 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4288 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
4289 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
4290
4291 // 6-bit char6 MST_ENTRY strings.
4292 Abbv = std::make_shared<BitCodeAbbrev>();
4293 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4294 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4295 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4296 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4297 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
4298
4299 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
4300 Abbv = std::make_shared<BitCodeAbbrev>();
4301 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
4302 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4303 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4304 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4305 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4306 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4307 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
4308
4310 forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
4311 StringRef Key = MPSE.getKey();
4312 const auto &Hash = MPSE.getValue();
4314 unsigned AbbrevToUse = Abbrev8Bit;
4315 if (Bits == SE_Char6)
4316 AbbrevToUse = Abbrev6Bit;
4317 else if (Bits == SE_Fixed7)
4318 AbbrevToUse = Abbrev7Bit;
4319
4320 auto ModuleId = ModuleIdMap.size();
4321 ModuleIdMap[Key] = ModuleId;
4322 Vals.push_back(ModuleId);
4323 // Use bytes_begin/end() for unsigned char iteration.
4324 Vals.append(Key.bytes_begin(), Key.bytes_end());
4325
4326 // Emit the finished record.
4327 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
4328
4329 // Emit an optional hash for the module now
4330 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
4331 Vals.assign(Hash.begin(), Hash.end());
4332 // Emit the hash record.
4333 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
4334 }
4335
4336 Vals.clear();
4337 });
4338 Stream.ExitBlock();
4339}
4340
4341/// Write the function type metadata related records that need to appear before
4342/// a function summary entry (whether per-module or combined).
4343template <typename Fn>
4345 FunctionSummary *FS,
4346 Fn GetValueID) {
4347 if (!FS->type_tests().empty())
4348 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
4349
4351
4352 auto WriteVFuncIdVec = [&](uint64_t Ty,
4354 if (VFs.empty())
4355 return;
4356 Record.clear();
4357 for (auto &VF : VFs) {
4358 Record.push_back(VF.GUID);
4359 Record.push_back(VF.Offset);
4360 }
4361 Stream.EmitRecord(Ty, Record);
4362 };
4363
4364 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
4365 FS->type_test_assume_vcalls());
4366 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
4367 FS->type_checked_load_vcalls());
4368
4369 auto WriteConstVCallVec = [&](uint64_t Ty,
4371 for (auto &VC : VCs) {
4372 Record.clear();
4373 Record.push_back(VC.VFunc.GUID);
4374 Record.push_back(VC.VFunc.Offset);
4375 llvm::append_range(Record, VC.Args);
4376 Stream.EmitRecord(Ty, Record);
4377 }
4378 };
4379
4380 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
4381 FS->type_test_assume_const_vcalls());
4382 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
4383 FS->type_checked_load_const_vcalls());
4384
4385 auto WriteRange = [&](ConstantRange Range) {
4387 assert(Range.getLower().getNumWords() == 1);
4388 assert(Range.getUpper().getNumWords() == 1);
4389 emitSignedInt64(Record, *Range.getLower().getRawData());
4390 emitSignedInt64(Record, *Range.getUpper().getRawData());
4391 };
4392
4393 if (!FS->paramAccesses().empty()) {
4394 Record.clear();
4395 for (auto &Arg : FS->paramAccesses()) {
4396 size_t UndoSize = Record.size();
4397 Record.push_back(Arg.ParamNo);
4398 WriteRange(Arg.Use);
4399 Record.push_back(Arg.Calls.size());
4400 for (auto &Call : Arg.Calls) {
4401 Record.push_back(Call.ParamNo);
4402 std::optional<unsigned> ValueID = GetValueID(Call.Callee);
4403 if (!ValueID) {
4404 // If ValueID is unknown we can't drop just this call, we must drop
4405 // entire parameter.
4406 Record.resize(UndoSize);
4407 break;
4408 }
4409 Record.push_back(*ValueID);
4410 WriteRange(Call.Offsets);
4411 }
4412 }
4413 if (!Record.empty())
4415 }
4416}
4417
4418/// Collect type IDs from type tests used by function.
4419static void
4421 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4422 if (!FS->type_tests().empty())
4423 for (auto &TT : FS->type_tests())
4424 ReferencedTypeIds.insert(TT);
4425
4426 auto GetReferencedTypesFromVFuncIdVec =
4428 for (auto &VF : VFs)
4429 ReferencedTypeIds.insert(VF.GUID);
4430 };
4431
4432 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4433 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4434
4435 auto GetReferencedTypesFromConstVCallVec =
4437 for (auto &VC : VCs)
4438 ReferencedTypeIds.insert(VC.VFunc.GUID);
4439 };
4440
4441 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4442 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4443}
4444
4446 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
4448 NameVals.push_back(args.size());
4449 llvm::append_range(NameVals, args);
4450
4451 NameVals.push_back(ByArg.TheKind);
4452 NameVals.push_back(ByArg.Info);
4453 NameVals.push_back(ByArg.Byte);
4454 NameVals.push_back(ByArg.Bit);
4455}
4456
4458 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4459 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
4460 NameVals.push_back(Id);
4461
4462 NameVals.push_back(Wpd.TheKind);
4463 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
4464 NameVals.push_back(Wpd.SingleImplName.size());
4465
4466 NameVals.push_back(Wpd.ResByArg.size());
4467 for (auto &A : Wpd.ResByArg)
4468 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
4469}
4470
4472 StringTableBuilder &StrtabBuilder,
4473 StringRef Id,
4474 const TypeIdSummary &Summary) {
4475 NameVals.push_back(StrtabBuilder.add(Id));
4476 NameVals.push_back(Id.size());
4477
4478 NameVals.push_back(Summary.TTRes.TheKind);
4479 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
4480 NameVals.push_back(Summary.TTRes.AlignLog2);
4481 NameVals.push_back(Summary.TTRes.SizeM1);
4482 NameVals.push_back(Summary.TTRes.BitMask);
4483 NameVals.push_back(Summary.TTRes.InlineBits);
4484
4485 for (auto &W : Summary.WPDRes)
4486 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
4487 W.second);
4488}
4489
4491 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4492 StringRef Id, const TypeIdCompatibleVtableInfo &Summary,
4494 NameVals.push_back(StrtabBuilder.add(Id));
4495 NameVals.push_back(Id.size());
4496
4497 for (auto &P : Summary) {
4498 NameVals.push_back(P.AddressPointOffset);
4499 NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
4500 }
4501}
4502
4503// Adds the allocation contexts to the CallStacks map. We simply use the
4504// size at the time the context was added as the CallStackId. This works because
4505// when we look up the call stacks later on we process the function summaries
4506// and their allocation records in the same exact order.
4508 FunctionSummary *FS, std::function<LinearFrameId(unsigned)> GetStackIndex,
4510 // The interfaces in ProfileData/MemProf.h use a type alias for a stack frame
4511 // id offset into the index of the full stack frames. The ModuleSummaryIndex
4512 // currently uses unsigned. Make sure these stay in sync.
4513 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4514 for (auto &AI : FS->allocs()) {
4515 for (auto &MIB : AI.MIBs) {
4516 SmallVector<unsigned> StackIdIndices;
4517 StackIdIndices.reserve(MIB.StackIdIndices.size());
4518 for (auto Id : MIB.StackIdIndices)
4519 StackIdIndices.push_back(GetStackIndex(Id));
4520 // The CallStackId is the size at the time this context was inserted.
4521 CallStacks.insert({CallStacks.size(), StackIdIndices});
4522 }
4523 }
4524}
4525
4526// Build the radix tree from the accumulated CallStacks, write out the resulting
4527// linearized radix tree array, and return the map of call stack positions into
4528// this array for use when writing the allocation records. The returned map is
4529// indexed by a CallStackId which in this case is implicitly determined by the
4530// order of function summaries and their allocation infos being written.
4533 BitstreamWriter &Stream, unsigned RadixAbbrev) {
4534 assert(!CallStacks.empty());
4535 DenseMap<unsigned, FrameStat> FrameHistogram =
4538 // We don't need a MemProfFrameIndexes map as we have already converted the
4539 // full stack id hash to a linear offset into the StackIds array.
4540 Builder.build(std::move(CallStacks), /*MemProfFrameIndexes=*/nullptr,
4541 FrameHistogram);
4542 Stream.EmitRecord(bitc::FS_CONTEXT_RADIX_TREE_ARRAY, Builder.getRadixArray(),
4543 RadixAbbrev);
4544 return Builder.takeCallStackPos();
4545}
4546
4548 BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
4549 unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule,
4550 std::function<unsigned(const ValueInfo &VI)> GetValueID,
4551 std::function<unsigned(unsigned)> GetStackIndex,
4552 bool WriteContextSizeInfoIndex,
4554 CallStackId &CallStackCount) {
4556
4557 for (auto &CI : FS->callsites()) {
4558 Record.clear();
4559 // Per module callsite clones should always have a single entry of
4560 // value 0.
4561 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4562 Record.push_back(GetValueID(CI.Callee));
4563 if (!PerModule) {
4564 Record.push_back(CI.StackIdIndices.size());
4565 Record.push_back(CI.Clones.size());
4566 }
4567 for (auto Id : CI.StackIdIndices)
4568 Record.push_back(GetStackIndex(Id));
4569 if (!PerModule)
4570 llvm::append_range(Record, CI.Clones);
4573 Record, CallsiteAbbrev);
4574 }
4575
4576 for (auto &AI : FS->allocs()) {
4577 Record.clear();
4578 // Per module alloc versions should always have a single entry of
4579 // value 0.
4580 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4581 Record.push_back(AI.MIBs.size());
4582 if (!PerModule)
4583 Record.push_back(AI.Versions.size());
4584 for (auto &MIB : AI.MIBs) {
4585 Record.push_back((uint8_t)MIB.AllocType);
4586 // The per-module summary always needs to include the alloc context, as we
4587 // use it during the thin link. For the combined index it is optional (see
4588 // comments where CombinedIndexMemProfContext is defined).
4589 if (PerModule || CombinedIndexMemProfContext) {
4590 // Record the index into the radix tree array for this context.
4591 assert(CallStackCount <= CallStackPos.size());
4592 Record.push_back(CallStackPos[CallStackCount++]);
4593 }
4594 }
4595 if (!PerModule)
4596 llvm::append_range(Record, AI.Versions);
4597 assert(AI.ContextSizeInfos.empty() ||
4598 AI.ContextSizeInfos.size() == AI.MIBs.size());
4599 // Optionally emit the context size information if it exists.
4600 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4601 // The abbreviation id for the context ids record should have been created
4602 // if we are emitting the per-module index, which is where we write this
4603 // info.
4604 assert(ContextIdAbbvId);
4605 SmallVector<uint32_t> ContextIds;
4606 // At least one context id per ContextSizeInfos entry (MIB), broken into 2
4607 // halves.
4608 ContextIds.reserve(AI.ContextSizeInfos.size() * 2);
4609 for (auto &Infos : AI.ContextSizeInfos) {
4610 Record.push_back(Infos.size());
4611 for (auto [FullStackId, TotalSize] : Infos) {
4612 // The context ids are emitted separately as a fixed width array,
4613 // which is more efficient than a VBR given that these hashes are
4614 // typically close to 64-bits. The max fixed width entry is 32 bits so
4615 // it is split into 2.
4616 ContextIds.push_back(static_cast<uint32_t>(FullStackId >> 32));
4617 ContextIds.push_back(static_cast<uint32_t>(FullStackId));
4618 Record.push_back(TotalSize);
4619 }
4620 }
4621 // The context ids are expected by the reader to immediately precede the
4622 // associated alloc info record.
4623 Stream.EmitRecord(bitc::FS_ALLOC_CONTEXT_IDS, ContextIds,
4624 ContextIdAbbvId);
4625 }
4626 Stream.EmitRecord(PerModule
4631 Record, AllocAbbrev);
4632 }
4633}
4634
4635// Helper to emit a single function summary record.
4636void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4637 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4638 unsigned ValueID, unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
4639 unsigned AllocAbbrev, unsigned ContextIdAbbvId, const Function &F,
4640 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4641 CallStackId &CallStackCount) {
4642 NameVals.push_back(ValueID);
4643
4644 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4645
4647 Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
4648 return {VE.getValueID(VI.getValue())};
4649 });
4650
4651 auto SpecialRefCnts = FS->specialRefCounts();
4652 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4653 NameVals.push_back(FS->instCount());
4654 NameVals.push_back(getEncodedFFlags(FS->fflags()));
4655 NameVals.push_back(FS->refs().size());
4656 NameVals.push_back(SpecialRefCnts.first); // rorefcnt
4657 NameVals.push_back(SpecialRefCnts.second); // worefcnt
4658
4659 for (auto &RI : FS->refs())
4660 NameVals.push_back(getValueId(RI));
4661
4662 for (auto &ECI : FS->calls()) {
4663 NameVals.push_back(getValueId(ECI.first));
4664 NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));
4665 }
4666
4667 // Emit the finished record.
4668 Stream.EmitRecord(bitc::FS_PERMODULE_PROFILE, NameVals, FSCallsProfileAbbrev);
4669 NameVals.clear();
4670
4672 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4673 /*PerModule*/ true,
4674 /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
4675 /*GetStackIndex*/ [&](unsigned I) { return I; },
4676 /*WriteContextSizeInfoIndex*/ true, CallStackPos, CallStackCount);
4677}
4678
4679// Collect the global value references in the given variable's initializer,
4680// and emit them in a summary record.
4681void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4682 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4683 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
4684 auto VI = Index->getValueInfo(V.getGUID());
4685 if (!VI || VI.getSummaryList().empty()) {
4686 // Only declarations should not have a summary (a declaration might however
4687 // have a summary if the def was in module level asm).
4688 assert(V.isDeclaration());
4689 return;
4690 }
4691 auto *Summary = VI.getSummaryList()[0].get();
4692 NameVals.push_back(VE.getValueID(&V));
4693 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
4694 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4695 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4696
4697 auto VTableFuncs = VS->vTableFuncs();
4698 if (!VTableFuncs.empty())
4699 NameVals.push_back(VS->refs().size());
4700
4701 unsigned SizeBeforeRefs = NameVals.size();
4702 for (auto &RI : VS->refs())
4703 NameVals.push_back(VE.getValueID(RI.getValue()));
4704 // Sort the refs for determinism output, the vector returned by FS->refs() has
4705 // been initialized from a DenseSet.
4706 llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
4707
4708 if (VTableFuncs.empty())
4710 FSModRefsAbbrev);
4711 else {
4712 // VTableFuncs pairs should already be sorted by offset.
4713 for (auto &P : VTableFuncs) {
4714 NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
4715 NameVals.push_back(P.VTableOffset);
4716 }
4717
4719 FSModVTableRefsAbbrev);
4720 }
4721 NameVals.clear();
4722}
4723
4724/// Emit the per-module summary section alongside the rest of
4725/// the module's bitcode.
4726void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4727 // By default we compile with ThinLTO if the module has a summary, but the
4728 // client can request full LTO with a module flag.
4729 bool IsThinLTO = true;
4730 if (auto *MD =
4731 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
4732 IsThinLTO = MD->getZExtValue();
4735 4);
4736
4737 Stream.EmitRecord(
4739 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
4740
4741 // Write the index flags.
4742 uint64_t Flags = 0;
4743 // Bits 1-3 are set only in the combined index, skip them.
4744 if (Index->enableSplitLTOUnit())
4745 Flags |= 0x8;
4746 if (Index->hasUnifiedLTO())
4747 Flags |= 0x200;
4748
4749 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
4750
4751 if (Index->begin() == Index->end()) {
4752 Stream.ExitBlock();
4753 return;
4754 }
4755
4756 auto Abbv = std::make_shared<BitCodeAbbrev>();
4757 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID));
4758 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4759 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
4760 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4761 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4762 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4763
4764 for (const auto &GVI : valueIds()) {
4766 ArrayRef<uint32_t>{GVI.second,
4767 static_cast<uint32_t>(GVI.first >> 32),
4768 static_cast<uint32_t>(GVI.first)},
4769 ValueGuidAbbrev);
4770 }
4771
4772 if (!Index->stackIds().empty()) {
4773 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4774 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4775 // numids x stackid
4776 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4777 // The stack ids are hashes that are close to 64 bits in size, so emitting
4778 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
4779 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4780 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4781 SmallVector<uint32_t> Vals;
4782 Vals.reserve(Index->stackIds().size() * 2);
4783 for (auto Id : Index->stackIds()) {
4784 Vals.push_back(static_cast<uint32_t>(Id >> 32));
4785 Vals.push_back(static_cast<uint32_t>(Id));
4786 }
4787 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
4788 }
4789
4790 unsigned ContextIdAbbvId = 0;
4792 // n x context id
4793 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4794 ContextIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_ALLOC_CONTEXT_IDS));
4795 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4796 // The context ids are hashes that are close to 64 bits in size, so emitting
4797 // as a pair of 32-bit fixed-width values is more efficient than a VBR if we
4798 // are emitting them for all MIBs. Otherwise we use VBR to better compress 0
4799 // values that are expected to more frequently occur in an alloc's memprof
4800 // summary.
4802 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4803 else
4804 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4805 ContextIdAbbvId = Stream.EmitAbbrev(std::move(ContextIdAbbv));
4806 }
4807
4808 // Abbrev for FS_PERMODULE_PROFILE.
4809 Abbv = std::make_shared<BitCodeAbbrev>();
4810 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
4811 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4812 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags
4813 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4814 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4815 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4816 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4817 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4818 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4819 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4820 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4821 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4822
4823 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4824 Abbv = std::make_shared<BitCodeAbbrev>();
4825 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
4826 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4827 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4828 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4829 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4830 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4831
4832 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4833 Abbv = std::make_shared<BitCodeAbbrev>();
4834 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
4835 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4836 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4837 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4838 // numrefs x valueid, n x (valueid , offset)
4839 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4840 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4841 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4842
4843 // Abbrev for FS_ALIAS.
4844 Abbv = std::make_shared<BitCodeAbbrev>();
4845 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4846 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4847 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4848 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4849 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4850
4851 // Abbrev for FS_TYPE_ID_METADATA
4852 Abbv = std::make_shared<BitCodeAbbrev>();
4853 Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
4854 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4855 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4856 // n x (valueid , offset)
4857 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4858 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4859 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4860
4861 Abbv = std::make_shared<BitCodeAbbrev>();
4862 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_CALLSITE_INFO));
4863 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4864 // n x stackidindex
4865 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4866 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4867 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4868
4869 Abbv = std::make_shared<BitCodeAbbrev>();
4870 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_ALLOC_INFO));
4871 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
4872 // n x (alloc type, context radix tree index)
4873 // optional: nummib x (numcontext x total size)
4874 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4875 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4876 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4877
4878 Abbv = std::make_shared<BitCodeAbbrev>();
4879 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CONTEXT_RADIX_TREE_ARRAY));
4880 // n x entry
4881 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4882 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4883 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4884
4885 // First walk through all the functions and collect the allocation contexts in
4886 // their associated summaries, for use in constructing a radix tree of
4887 // contexts. Note that we need to do this in the same order as the functions
4888 // are processed further below since the call stack positions in the resulting
4889 // radix tree array are identified based on this order.
4890 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
4891 for (const Function &F : M) {
4892 // Summary emission does not support anonymous functions, they have to be
4893 // renamed using the anonymous function renaming pass.
4894 if (!F.hasName())
4895 report_fatal_error("Unexpected anonymous function when writing summary");
4896
4897 ValueInfo VI = Index->getValueInfo(F.getGUID());
4898 if (!VI || VI.getSummaryList().empty()) {
4899 // Only declarations should not have a summary (a declaration might
4900 // however have a summary if the def was in module level asm).
4901 assert(F.isDeclaration());
4902 continue;
4903 }
4904 auto *Summary = VI.getSummaryList()[0].get();
4905 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4907 FS, /*GetStackIndex*/ [](unsigned I) { return I; }, CallStacks);
4908 }
4909 // Finalize the radix tree, write it out, and get the map of positions in the
4910 // linearized tree array.
4911 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
4912 if (!CallStacks.empty()) {
4913 CallStackPos =
4914 writeMemoryProfileRadixTree(std::move(CallStacks), Stream, RadixAbbrev);
4915 }
4916
4917 // Keep track of the current index into the CallStackPos map.
4918 CallStackId CallStackCount = 0;
4919
4920 SmallVector<uint64_t, 64> NameVals;
4921 // Iterate over the list of functions instead of the Index to
4922 // ensure the ordering is stable.
4923 for (const Function &F : M) {
4924 // Summary emission does not support anonymous functions, they have to
4925 // renamed using the anonymous function renaming pass.
4926 if (!F.hasName())
4927 report_fatal_error("Unexpected anonymous function when writing summary");
4928
4929 ValueInfo VI = Index->getValueInfo(F.getGUID());
4930 if (!VI || VI.getSummaryList().empty()) {
4931 // Only declarations should not have a summary (a declaration might
4932 // however have a summary if the def was in module level asm).
4933 assert(F.isDeclaration());
4934 continue;
4935 }
4936 auto *Summary = VI.getSummaryList()[0].get();
4937 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
4938 FSCallsProfileAbbrev, CallsiteAbbrev,
4939 AllocAbbrev, ContextIdAbbvId, F,
4940 CallStackPos, CallStackCount);
4941 }
4942
4943 // Capture references from GlobalVariable initializers, which are outside
4944 // of a function scope.
4945 for (const GlobalVariable &G : M.globals())
4946 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4947 FSModVTableRefsAbbrev);
4948
4949 for (const GlobalAlias &A : M.aliases()) {
4950 auto *Aliasee = A.getAliaseeObject();
4951 // Skip ifunc and nameless functions which don't have an entry in the
4952 // summary.
4953 if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
4954 continue;
4955 auto AliasId = VE.getValueID(&A);
4956 auto AliaseeId = VE.getValueID(Aliasee);
4957 NameVals.push_back(AliasId);
4958 auto *Summary = Index->getGlobalValueSummary(A);
4959 AliasSummary *AS = cast<AliasSummary>(Summary);
4960 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4961 NameVals.push_back(AliaseeId);
4962 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4963 NameVals.clear();
4964 }
4965
4966 for (auto &S : Index->typeIdCompatibleVtableMap()) {
4967 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4968 S.second, VE);
4969 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4970 TypeIdCompatibleVtableAbbrev);
4971 NameVals.clear();
4972 }
4973
4974 if (Index->getBlockCount())
4976 ArrayRef<uint64_t>{Index->getBlockCount()});
4977
4978 Stream.ExitBlock();
4979}
4980
4981/// Emit the combined summary section into the combined index file.
4982void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4984 Stream.EmitRecord(
4986 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
4987
4988 // Write the index flags.
4989 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
4990
4991 auto Abbv = std::make_shared<BitCodeAbbrev>();
4992 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID));
4993 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4994 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
4995 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4996 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4997 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4998
4999 for (const auto &GVI : valueIds()) {
5001 ArrayRef<uint32_t>{GVI.second,
5002 static_cast<uint32_t>(GVI.first >> 32),
5003 static_cast<uint32_t>(GVI.first)},
5004 ValueGuidAbbrev);
5005 }
5006
5007 // Write the stack ids used by this index, which will be a subset of those in
5008 // the full index in the case of distributed indexes.
5009 if (!StackIds.empty()) {
5010 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5011 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
5012 // numids x stackid
5013 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5014 // The stack ids are hashes that are close to 64 bits in size, so emitting
5015 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
5016 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
5017 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
5018 SmallVector<uint32_t> Vals;
5019 Vals.reserve(StackIds.size() * 2);
5020 for (auto Id : StackIds) {
5021 Vals.push_back(static_cast<uint32_t>(Id >> 32));
5022 Vals.push_back(static_cast<uint32_t>(Id));
5023 }
5024 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
5025 }
5026
5027 // Abbrev for FS_COMBINED_PROFILE.
5028 Abbv = std::make_shared<BitCodeAbbrev>();
5029 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
5030 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5031 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
5032 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5033 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
5034 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
5035 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
5036 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
5037 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
5038 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
5039 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
5040 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5041 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5042 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5043
5044 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
5045 Abbv = std::make_shared<BitCodeAbbrev>();
5046 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
5047 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5048 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
5049 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5050 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
5051 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5052 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5053
5054 // Abbrev for FS_COMBINED_ALIAS.
5055 Abbv = std::make_shared<BitCodeAbbrev>();
5056 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
5057 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5058 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
5059 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5060 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5061 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5062
5063 Abbv = std::make_shared<BitCodeAbbrev>();
5064 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_CALLSITE_INFO));
5065 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5066 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices
5067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
5068 // numstackindices x stackidindex, numver x version
5069 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5070 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5071 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5072
5073 Abbv = std::make_shared<BitCodeAbbrev>();
5074 Abbv->Add(BitCodeAbbrevOp(CombinedIndexMemProfContext
5077 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
5078 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
5079 // nummib x (alloc type, context radix tree index),
5080 // numver x version
5081 // optional: nummib x total size
5082 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5083 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5084 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5085
5086 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) -> bool {
5087 if (DecSummaries == nullptr)
5088 return false;
5089 return DecSummaries->count(GVS);
5090 };
5091
5092 // The aliases are emitted as a post-pass, and will point to the value
5093 // id of the aliasee. Save them in a vector for post-processing.
5095
5096 // Save the value id for each summary for alias emission.
5097 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5098
5099 SmallVector<uint64_t, 64> NameVals;
5100
5101 // Set that will be populated during call to writeFunctionTypeMetadataRecords
5102 // with the type ids referenced by this index file.
5103 std::set<GlobalValue::GUID> ReferencedTypeIds;
5104
5105 // For local linkage, we also emit the original name separately
5106 // immediately after the record.
5107 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5108 // We don't need to emit the original name if we are writing the index for
5109 // distributed backends (in which case ModuleToSummariesForIndex is
5110 // non-null). The original name is only needed during the thin link, since
5111 // for SamplePGO the indirect call targets for local functions have
5112 // have the original name annotated in profile.
5113 // Continue to emit it when writing out the entire combined index, which is
5114 // used in testing the thin link via llvm-lto.
5115 if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
5116 return;
5117 NameVals.push_back(S.getOriginalName());
5119 NameVals.clear();
5120 };
5121
5122 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5124 Abbv = std::make_shared<BitCodeAbbrev>();
5125 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CONTEXT_RADIX_TREE_ARRAY));
5126 // n x entry
5127 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5128 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5129 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5130
5131 // First walk through all the functions and collect the allocation contexts
5132 // in their associated summaries, for use in constructing a radix tree of
5133 // contexts. Note that we need to do this in the same order as the functions
5134 // are processed further below since the call stack positions in the
5135 // resulting radix tree array are identified based on this order.
5136 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5137 forEachSummary([&](GVInfo I, bool IsAliasee) {
5138 // Don't collect this when invoked for an aliasee, as it is not needed for
5139 // the alias summary. If the aliasee is to be imported, we will invoke
5140 // this separately with IsAliasee=false.
5141 if (IsAliasee)
5142 return;
5143 GlobalValueSummary *S = I.second;
5144 assert(S);
5145 auto *FS = dyn_cast<FunctionSummary>(S);
5146 if (!FS)
5147 return;
5149 FS,
5150 /*GetStackIndex*/
5151 [&](unsigned I) {
5152 // Get the corresponding index into the list of StackIds actually
5153 // being written for this combined index (which may be a subset in
5154 // the case of distributed indexes).
5155 assert(StackIdIndicesToIndex.contains(I));
5156 return StackIdIndicesToIndex[I];
5157 },
5158 CallStacks);
5159 });
5160 // Finalize the radix tree, write it out, and get the map of positions in
5161 // the linearized tree array.
5162 if (!CallStacks.empty()) {
5163 CallStackPos = writeMemoryProfileRadixTree(std::move(CallStacks), Stream,
5164 RadixAbbrev);
5165 }
5166 }
5167
5168 // Keep track of the current index into the CallStackPos map. Not used if
5169 // CombinedIndexMemProfContext is false.
5170 CallStackId CallStackCount = 0;
5171
5172 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5173 forEachSummary([&](GVInfo I, bool IsAliasee) {
5174 GlobalValueSummary *S = I.second;
5175 assert(S);
5176 DefOrUseGUIDs.insert(I.first);
5177 for (const ValueInfo &VI : S->refs())
5178 DefOrUseGUIDs.insert(VI.getGUID());
5179
5180 auto ValueId = getValueId(I.first);
5181 assert(ValueId);
5182 SummaryToValueIdMap[S] = *ValueId;
5183
5184 // If this is invoked for an aliasee, we want to record the above
5185 // mapping, but then not emit a summary entry (if the aliasee is
5186 // to be imported, we will invoke this separately with IsAliasee=false).
5187 if (IsAliasee)
5188 return;
5189
5190 if (auto *AS = dyn_cast<AliasSummary>(S)) {
5191 // Will process aliases as a post-pass because the reader wants all
5192 // global to be loaded first.
5193 Aliases.push_back(AS);
5194 return;
5195 }
5196
5197 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
5198 NameVals.push_back(*ValueId);
5199 assert(ModuleIdMap.count(VS->modulePath()));
5200 NameVals.push_back(ModuleIdMap[VS->modulePath()]);
5201 NameVals.push_back(
5202 getEncodedGVSummaryFlags(VS->flags(), shouldImportValueAsDecl(VS)));
5203 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
5204 for (auto &RI : VS->refs()) {
5205 auto RefValueId = getValueId(RI.getGUID());
5206 if (!RefValueId)
5207 continue;
5208 NameVals.push_back(*RefValueId);
5209 }
5210
5211 // Emit the finished record.
5213 FSModRefsAbbrev);
5214 NameVals.clear();
5215 MaybeEmitOriginalName(*S);
5216 return;
5217 }
5218
5219 auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> {
5220 if (!VI)
5221 return std::nullopt;
5222 return getValueId(VI.getGUID());
5223 };
5224
5225 auto *FS = cast<FunctionSummary>(S);
5226 writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
5227 getReferencedTypeIds(FS, ReferencedTypeIds);
5228
5229 NameVals.push_back(*ValueId);
5230 assert(ModuleIdMap.count(FS->modulePath()));
5231 NameVals.push_back(ModuleIdMap[FS->modulePath()]);
5232 NameVals.push_back(
5233 getEncodedGVSummaryFlags(FS->flags(), shouldImportValueAsDecl(FS)));
5234 NameVals.push_back(FS->instCount());
5235 NameVals.push_back(getEncodedFFlags(FS->fflags()));
5236 // TODO: Stop writing entry count and bump bitcode version.
5237 NameVals.push_back(0 /* EntryCount */);
5238
5239 // Fill in below
5240 NameVals.push_back(0); // numrefs
5241 NameVals.push_back(0); // rorefcnt
5242 NameVals.push_back(0); // worefcnt
5243
5244 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5245 for (auto &RI : FS->refs()) {
5246 auto RefValueId = getValueId(RI.getGUID());
5247 if (!RefValueId)
5248 continue;
5249 NameVals.push_back(*RefValueId);
5250 if (RI.isReadOnly())
5251 RORefCnt++;
5252 else if (RI.isWriteOnly())
5253 WORefCnt++;
5254 Count++;
5255 }
5256 NameVals[6] = Count;
5257 NameVals[7] = RORefCnt;
5258 NameVals[8] = WORefCnt;
5259
5260 for (auto &EI : FS->calls()) {
5261 // If this GUID doesn't have a value id, it doesn't have a function
5262 // summary and we don't need to record any calls to it.
5263 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5264 if (!CallValueId)
5265 continue;
5266 NameVals.push_back(*CallValueId);
5267 NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second));
5268 }
5269
5270 // Emit the finished record.
5271 Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals,
5272 FSCallsProfileAbbrev);
5273 NameVals.clear();
5274
5276 Stream, FS, CallsiteAbbrev, AllocAbbrev, /*ContextIdAbbvId*/ 0,
5277 /*PerModule*/ false,
5278 /*GetValueId*/
5279 [&](const ValueInfo &VI) -> unsigned {
5280 std::optional<unsigned> ValueID = GetValueId(VI);
5281 // This can happen in shared index files for distributed ThinLTO if
5282 // the callee function summary is not included. Record 0 which we
5283 // will have to deal with conservatively when doing any kind of
5284 // validation in the ThinLTO backends.
5285 if (!ValueID)
5286 return 0;
5287 return *ValueID;
5288 },
5289 /*GetStackIndex*/
5290 [&](unsigned I) {
5291 // Get the corresponding index into the list of StackIds actually
5292 // being written for this combined index (which may be a subset in
5293 // the case of distributed indexes).
5294 assert(StackIdIndicesToIndex.contains(I));
5295 return StackIdIndicesToIndex[I];
5296 },
5297 /*WriteContextSizeInfoIndex*/ false, CallStackPos, CallStackCount);
5298
5299 MaybeEmitOriginalName(*S);
5300 });
5301
5302 for (auto *AS : Aliases) {
5303 auto AliasValueId = SummaryToValueIdMap[AS];
5304 assert(AliasValueId);
5305 NameVals.push_back(AliasValueId);
5306 assert(ModuleIdMap.count(AS->modulePath()));
5307 NameVals.push_back(ModuleIdMap[AS->modulePath()]);
5308 NameVals.push_back(
5309 getEncodedGVSummaryFlags(AS->flags(), shouldImportValueAsDecl(AS)));
5310 // Set value id to 0 when an alias is imported but the aliasee summary is
5311 // not contained in the index.
5312 auto AliaseeValueId =
5313 AS->hasAliasee() ? SummaryToValueIdMap[&AS->getAliasee()] : 0;
5314 NameVals.push_back(AliaseeValueId);
5315
5316 // Emit the finished record.
5317 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
5318 NameVals.clear();
5319 MaybeEmitOriginalName(*AS);
5320
5321 if (AS->hasAliasee())
5322 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
5323 getReferencedTypeIds(FS, ReferencedTypeIds);
5324 }
5325
5327 auto EmitCfiFunctions = [&](const CfiFunctionIndex &CfiIndex,
5329 if (CfiIndex.empty())
5330 return;
5331 for (GlobalValue::GUID GUID : DefOrUseGUIDs) {
5332 auto Names = CfiIndex.getNamesForGUID(GUID);
5333 for (StringRef Name : Names)
5334 Functions.push_back({Name, GUID});
5335 }
5336 if (Functions.empty())
5337 return;
5338 llvm::sort(Functions);
5339 for (const auto &Record : Functions) {
5340 NameVals.push_back(Record.second);
5341 NameVals.push_back(StrtabBuilder.add(Record.first));
5342 NameVals.push_back(Record.first.size());
5343 }
5344 Stream.EmitRecord(Code, NameVals);
5345 NameVals.clear();
5346 Functions.clear();
5347 };
5348
5349 EmitCfiFunctions(Index.cfiFunctionDefs(), bitc::FS_CFI_FUNCTION_DEFS);
5350 EmitCfiFunctions(Index.cfiFunctionDecls(), bitc::FS_CFI_FUNCTION_DECLS);
5351
5352 // Walk the GUIDs that were referenced, and write the
5353 // corresponding type id records.
5354 for (auto &T : ReferencedTypeIds) {
5355 auto TidIter = Index.typeIds().equal_range(T);
5356 for (const auto &[GUID, TypeIdPair] : make_range(TidIter)) {
5357 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, TypeIdPair.first,
5358 TypeIdPair.second);
5359 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
5360 NameVals.clear();
5361 }
5362 }
5363
5364 if (Index.getBlockCount())
5366 ArrayRef<uint64_t>{Index.getBlockCount()});
5367
5368 Stream.ExitBlock();
5369}
5370
5371/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
5372/// current llvm version, and a record for the epoch number.
5375
5376 // Write the "user readable" string identifying the bitcode producer
5377 auto Abbv = std::make_shared<BitCodeAbbrev>();
5381 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5383 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5384
5385 // Write the epoch version
5386 Abbv = std::make_shared<BitCodeAbbrev>();
5389 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5390 constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
5391 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
5392 Stream.ExitBlock();
5393}
5394
5395void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5396 // Emit the module's hash.
5397 // MODULE_CODE_HASH: [5*i32]
5398 if (GenerateHash) {
5399 uint32_t Vals[5];
5400 Hasher.update(ArrayRef<uint8_t>(
5401 reinterpret_cast<const uint8_t *>(View.data()), View.size()));
5402 std::array<uint8_t, 20> Hash = Hasher.result();
5403 for (int Pos = 0; Pos < 20; Pos += 4) {
5404 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
5405 }
5406
5407 // Emit the finished record.
5408 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
5409
5410 if (ModHash)
5411 // Save the written hash value.
5412 llvm::copy(Vals, std::begin(*ModHash));
5413 }
5414}
5415
5416void ModuleBitcodeWriter::write() {
5418
5420 // We will want to write the module hash at this point. Block any flushing so
5421 // we can have access to the whole underlying data later.
5422 Stream.markAndBlockFlushing();
5423
5424 writeModuleVersion();
5425
5426 // Emit blockinfo, which defines the standard abbreviations etc.
5427 writeBlockInfo();
5428
5429 // Emit information describing all of the types in the module.
5430 writeTypeTable();
5431
5432 // Emit information about attribute groups.
5433 writeAttributeGroupTable();
5434
5435 // Emit information about parameter attributes.
5436 writeAttributeTable();
5437
5438 writeComdats();
5439
5440 // Emit top-level description of module, including target triple, inline asm,
5441 // descriptors for global variables, and function prototype info.
5442 writeModuleInfo();
5443
5444 // Emit constants.
5445 writeModuleConstants();
5446
5447 // Emit metadata kind names.
5448 writeModuleMetadataKinds();
5449
5450 // Emit metadata.
5451 writeModuleMetadata();
5452
5453 // Emit module-level use-lists.
5455 writeUseListBlock(nullptr);
5456
5457 writeOperandBundleTags();
5458 writeSyncScopeNames();
5459
5460 // Emit function bodies.
5461 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5462 for (const Function &F : M)
5463 if (!F.isDeclaration())
5464 writeFunction(F, FunctionToBitcodeIndex);
5465
5466 // Need to write after the above call to WriteFunction which populates
5467 // the summary information in the index.
5468 if (Index)
5469 writePerModuleGlobalValueSummary();
5470
5471 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5472
5473 writeModuleHash(Stream.getMarkedBufferAndResumeFlushing());
5474
5475 Stream.ExitBlock();
5476}
5477
5479 uint32_t &Position) {
5480 support::endian::write32le(&Buffer[Position], Value);
5481 Position += 4;
5482}
5483
5484/// If generating a bc file on darwin, we have to emit a
5485/// header and trailer to make it compatible with the system archiver. To do
5486/// this we emit the following header, and then emit a trailer that pads the
5487/// file out to be a multiple of 16 bytes.
5488///
5489/// struct bc_header {
5490/// uint32_t Magic; // 0x0B17C0DE
5491/// uint32_t Version; // Version, currently always 0.
5492/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
5493/// uint32_t BitcodeSize; // Size of traditional bitcode file.
5494/// uint32_t CPUType; // CPU specifier.
5495/// ... potentially more later ...
5496/// };
5498 const Triple &TT) {
5499 unsigned CPUType = ~0U;
5500
5501 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
5502 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
5503 // number from /usr/include/mach/machine.h. It is ok to reproduce the
5504 // specific constants here because they are implicitly part of the Darwin ABI.
5505 enum {
5506 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5507 DARWIN_CPU_TYPE_X86 = 7,
5508 DARWIN_CPU_TYPE_ARM = 12,
5509 DARWIN_CPU_TYPE_POWERPC = 18
5510 };
5511
5512 Triple::ArchType Arch = TT.getArch();
5513 if (Arch == Triple::x86_64)
5514 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5515 else if (Arch == Triple::x86)
5516 CPUType = DARWIN_CPU_TYPE_X86;
5517 else if (Arch == Triple::ppc)
5518 CPUType = DARWIN_CPU_TYPE_POWERPC;
5519 else if (Arch == Triple::ppc64)
5520 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5521 else if (Arch == Triple::arm || Arch == Triple::thumb)
5522 CPUType = DARWIN_CPU_TYPE_ARM;
5523
5524 // Traditional Bitcode starts after header.
5525 assert(Buffer.size() >= BWH_HeaderSize &&
5526 "Expected header size to be reserved");
5527 unsigned BCOffset = BWH_HeaderSize;
5528 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
5529
5530 // Write the magic and version.
5531 unsigned Position = 0;
5532 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
5533 writeInt32ToBuffer(0, Buffer, Position); // Version.
5534 writeInt32ToBuffer(BCOffset, Buffer, Position);
5535 writeInt32ToBuffer(BCSize, Buffer, Position);
5536 writeInt32ToBuffer(CPUType, Buffer, Position);
5537
5538 // If the file is not a multiple of 16 bytes, insert dummy padding.
5539 while (Buffer.size() & 15)
5540 Buffer.push_back(0);
5541}
5542
5543/// Helper to write the header common to all bitcode files.
5545 // Emit the file header.
5546 Stream.Emit((unsigned)'B', 8);
5547 Stream.Emit((unsigned)'C', 8);
5548 Stream.Emit(0x0, 4);
5549 Stream.Emit(0xC, 4);
5550 Stream.Emit(0xE, 4);
5551 Stream.Emit(0xD, 4);
5552}
5553
5555 : Stream(new BitstreamWriter(Buffer)) {
5556 writeBitcodeHeader(*Stream);
5557}
5558
5563
5565
5566void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
5567 Stream->EnterSubblock(Block, 3);
5568
5569 auto Abbv = std::make_shared<BitCodeAbbrev>();
5570 Abbv->Add(BitCodeAbbrevOp(Record));
5572 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
5573
5574 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
5575
5576 Stream->ExitBlock();
5577}
5578
5580 assert(!WroteStrtab && !WroteSymtab);
5581
5582 // If any module has module-level inline asm, we will require a registered asm
5583 // parser for the target so that we can create an accurate symbol table for
5584 // the module.
5585 for (Module *M : Mods) {
5586 if (M->getModuleInlineAsm().empty())
5587 continue;
5588
5589 std::string Err;
5590 const Triple TT(M->getTargetTriple());
5591 const Target *T = TargetRegistry::lookupTarget(TT, Err);
5592 if (!T || !T->hasMCAsmParser())
5593 return;
5594 }
5595
5596 WroteSymtab = true;
5597 SmallVector<char, 0> Symtab;
5598 // The irsymtab::build function may be unable to create a symbol table if the
5599 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
5600 // table is not required for correctness, but we still want to be able to
5601 // write malformed modules to bitcode files, so swallow the error.
5602 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
5603 consumeError(std::move(E));
5604 return;
5605 }
5606
5608 {Symtab.data(), Symtab.size()});
5609}
5610
5612 assert(!WroteStrtab);
5613
5614 std::vector<char> Strtab;
5615 StrtabBuilder.finalizeInOrder();
5616 Strtab.resize(StrtabBuilder.getSize());
5617 StrtabBuilder.write((uint8_t *)Strtab.data());
5618
5620 {Strtab.data(), Strtab.size()});
5621
5622 WroteStrtab = true;
5623}
5624
5626 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
5627 WroteStrtab = true;
5628}
5629
5631 bool ShouldPreserveUseListOrder,
5632 const ModuleSummaryIndex *Index,
5633 bool GenerateHash, ModuleHash *ModHash) {
5634 assert(!WroteStrtab);
5635
5636 // The Mods vector is used by irsymtab::build, which requires non-const
5637 // Modules in case it needs to materialize metadata. But the bitcode writer
5638 // requires that the module is materialized, so we can cast to non-const here,
5639 // after checking that it is in fact materialized.
5640 assert(M.isMaterialized());
5641 Mods.push_back(const_cast<Module *>(&M));
5642
5643 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5644 ShouldPreserveUseListOrder, Index,
5645 GenerateHash, ModHash);
5646 ModuleWriter.write();
5647}
5648
5650 const ModuleSummaryIndex *Index,
5651 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5652 const GVSummaryPtrSet *DecSummaries) {
5653 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5654 ModuleToSummariesForIndex);
5655 IndexWriter.write();
5656}
5657
5658/// Write the specified module to the specified output stream.
5660 bool ShouldPreserveUseListOrder,
5661 const ModuleSummaryIndex *Index,
5662 bool GenerateHash, ModuleHash *ModHash) {
5663 auto Write = [&](BitcodeWriter &Writer) {
5664 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5665 ModHash);
5666 Writer.writeSymtab();
5667 Writer.writeStrtab();
5668 };
5669 Triple TT(M.getTargetTriple());
5670 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5671 // If this is darwin or another generic macho target, reserve space for the
5672 // header. Note that the header is computed *after* the output is known, so
5673 // we currently explicitly use a buffer, write to it, and then subsequently
5674 // flush to Out.
5675 SmallVector<char, 0> Buffer;
5676 Buffer.reserve(256 * 1024);
5677 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
5678 BitcodeWriter Writer(Buffer);
5679 Write(Writer);
5680 emitDarwinBCHeaderAndTrailer(Buffer, TT);
5681 Out.write(Buffer.data(), Buffer.size());
5682 } else {
5683 BitcodeWriter Writer(Out);
5684 Write(Writer);
5685 }
5686}
5687
5688void IndexBitcodeWriter::write() {
5690
5691 writeModuleVersion();
5692
5693 // Write the module paths in the combined index.
5694 writeModStrings();
5695
5696 // Write the summary combined index records.
5697 writeCombinedGlobalValueSummary();
5698
5699 Stream.ExitBlock();
5700}
5701
5702// Write the specified module summary index to the given raw output stream,
5703// where it will be written in a new bitcode block. This is used when
5704// writing the combined index file for ThinLTO. When writing a subset of the
5705// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
5707 const ModuleSummaryIndex &Index, raw_ostream &Out,
5708 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5709 const GVSummaryPtrSet *DecSummaries) {
5710 SmallVector<char, 0> Buffer;
5711 Buffer.reserve(256 * 1024);
5712
5713 BitcodeWriter Writer(Buffer);
5714 Writer.writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5715 Writer.writeStrtab();
5716
5717 Out.write((char *)&Buffer.front(), Buffer.size());
5718}
5719
5720namespace {
5721
5722/// Class to manage the bitcode writing for a thin link bitcode file.
5723class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
5724 /// ModHash is for use in ThinLTO incremental build, generated while writing
5725 /// the module bitcode file.
5726 const ModuleHash *ModHash;
5727
5728public:
5729 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
5730 BitstreamWriter &Stream,
5731 const ModuleSummaryIndex &Index,
5732 const ModuleHash &ModHash)
5733 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5734 /*ShouldPreserveUseListOrder=*/false, &Index),
5735 ModHash(&ModHash) {}
5736
5737 void write();
5738
5739private:
5740 void writeSimplifiedModuleInfo();
5741};
5742
5743} // end anonymous namespace
5744
5745// This function writes a simpilified module info for thin link bitcode file.
5746// It only contains the source file name along with the name(the offset and
5747// size in strtab) and linkage for global values. For the global value info
5748// entry, in order to keep linkage at offset 5, there are three zeros used
5749// as padding.
5750void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5752 // Emit the module's source file name.
5753 {
5754 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
5756 if (Bits == SE_Char6)
5757 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
5758 else if (Bits == SE_Fixed7)
5759 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
5760
5761 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5762 auto Abbv = std::make_shared<BitCodeAbbrev>();
5765 Abbv->Add(AbbrevOpToUse);
5766 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5767
5768 for (const auto P : M.getSourceFileName())
5769 Vals.push_back((unsigned char)P);
5770
5771 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
5772 Vals.clear();
5773 }
5774
5775 // Emit the global variable information.
5776 for (const GlobalVariable &GV : M.globals()) {
5777 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
5778 Vals.push_back(StrtabBuilder.add(GV.getName()));
5779 Vals.push_back(GV.getName().size());
5780 Vals.push_back(0);
5781 Vals.push_back(0);
5782 Vals.push_back(0);
5783 Vals.push_back(getEncodedLinkage(GV));
5784
5786 Vals.clear();
5787 }
5788
5789 // Emit the function proto information.
5790 for (const Function &F : M) {
5791 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
5792 Vals.push_back(StrtabBuilder.add(F.getName()));
5793 Vals.push_back(F.getName().size());
5794 Vals.push_back(0);
5795 Vals.push_back(0);
5796 Vals.push_back(0);
5798
5800 Vals.clear();
5801 }
5802
5803 // Emit the alias information.
5804 for (const GlobalAlias &A : M.aliases()) {
5805 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
5806 Vals.push_back(StrtabBuilder.add(A.getName()));
5807 Vals.push_back(A.getName().size());
5808 Vals.push_back(0);
5809 Vals.push_back(0);
5810 Vals.push_back(0);
5812
5813 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
5814 Vals.clear();
5815 }
5816
5817 // Emit the ifunc information.
5818 for (const GlobalIFunc &I : M.ifuncs()) {
5819 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
5820 Vals.push_back(StrtabBuilder.add(I.getName()));
5821 Vals.push_back(I.getName().size());
5822 Vals.push_back(0);
5823 Vals.push_back(0);
5824 Vals.push_back(0);
5826
5827 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
5828 Vals.clear();
5829 }
5830}
5831
5832void ThinLinkBitcodeWriter::write() {
5834
5835 writeModuleVersion();
5836
5837 writeSimplifiedModuleInfo();
5838
5839 writePerModuleGlobalValueSummary();
5840
5841 // Write module hash.
5843
5844 Stream.ExitBlock();
5845}
5846
5848 const ModuleSummaryIndex &Index,
5849 const ModuleHash &ModHash) {
5850 assert(!WroteStrtab);
5851
5852 // The Mods vector is used by irsymtab::build, which requires non-const
5853 // Modules in case it needs to materialize metadata. But the bitcode writer
5854 // requires that the module is materialized, so we can cast to non-const here,
5855 // after checking that it is in fact materialized.
5856 assert(M.isMaterialized());
5857 Mods.push_back(const_cast<Module *>(&M));
5858
5859 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
5860 ModHash);
5861 ThinLinkWriter.write();
5862}
5863
5864// Write the specified thin link bitcode file to the given raw output stream,
5865// where it will be written in a new bitcode block. This is used when
5866// writing the per-module index file for ThinLTO.
5868 const ModuleSummaryIndex &Index,
5869 const ModuleHash &ModHash) {
5870 SmallVector<char, 0> Buffer;
5871 Buffer.reserve(256 * 1024);
5872
5873 BitcodeWriter Writer(Buffer);
5874 Writer.writeThinLinkBitcode(M, Index, ModHash);
5875 Writer.writeSymtab();
5876 Writer.writeStrtab();
5877
5878 Out.write((char *)&Buffer.front(), Buffer.size());
5879}
5880
5881static const char *getSectionNameForBitcode(const Triple &T) {
5882 switch (T.getObjectFormat()) {
5883 case Triple::MachO:
5884 return "__LLVM,__bitcode";
5885 case Triple::COFF:
5886 case Triple::ELF:
5887 case Triple::Wasm:
5889 return ".llvmbc";
5890 case Triple::GOFF:
5891 llvm_unreachable("GOFF is not yet implemented");
5892 break;
5893 case Triple::SPIRV:
5894 if (T.getVendor() == Triple::AMD)
5895 return ".llvmbc";
5896 llvm_unreachable("SPIRV is not yet implemented");
5897 break;
5898 case Triple::XCOFF:
5899 llvm_unreachable("XCOFF is not yet implemented");
5900 break;
5902 llvm_unreachable("DXContainer is not yet implemented");
5903 break;
5904 }
5905 llvm_unreachable("Unimplemented ObjectFormatType");
5906}
5907
5908static const char *getSectionNameForCommandline(const Triple &T) {
5909 switch (T.getObjectFormat()) {
5910 case Triple::MachO:
5911 return "__LLVM,__cmdline";
5912 case Triple::COFF:
5913 case Triple::ELF:
5914 case Triple::Wasm:
5916 return ".llvmcmd";
5917 case Triple::GOFF:
5918 llvm_unreachable("GOFF is not yet implemented");
5919 break;
5920 case Triple::SPIRV:
5921 if (T.getVendor() == Triple::AMD)
5922 return ".llvmcmd";
5923 llvm_unreachable("SPIRV is not yet implemented");
5924 break;
5925 case Triple::XCOFF:
5926 llvm_unreachable("XCOFF is not yet implemented");
5927 break;
5929 llvm_unreachable("DXC is not yet implemented");
5930 break;
5931 }
5932 llvm_unreachable("Unimplemented ObjectFormatType");
5933}
5934
5936 bool EmbedBitcode, bool EmbedCmdline,
5937 const std::vector<uint8_t> &CmdArgs) {
5938 // Save llvm.compiler.used and remove it.
5941 GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
5942 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
5943 : PointerType::getUnqual(M.getContext());
5944 for (auto *GV : UsedGlobals) {
5945 if (GV->getName() != "llvm.embedded.module" &&
5946 GV->getName() != "llvm.cmdline")
5947 UsedArray.push_back(
5949 }
5950 if (Used)
5951 Used->eraseFromParent();
5952
5953 // Embed the bitcode for the llvm module.
5954 std::string Data;
5955 ArrayRef<uint8_t> ModuleData;
5956 Triple T(M.getTargetTriple());
5957
5958 if (EmbedBitcode) {
5959 if (Buf.getBufferSize() == 0 ||
5960 !isBitcode((const unsigned char *)Buf.getBufferStart(),
5961 (const unsigned char *)Buf.getBufferEnd())) {
5962 // If the input is LLVM Assembly, bitcode is produced by serializing
5963 // the module. Use-lists order need to be preserved in this case.
5965 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
5966 ModuleData =
5967 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
5968 } else
5969 // If the input is LLVM bitcode, write the input byte stream directly.
5970 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
5971 Buf.getBufferSize());
5972 }
5973 llvm::Constant *ModuleConstant =
5974 llvm::ConstantDataArray::get(M.getContext(), ModuleData);
5976 M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
5977 ModuleConstant);
5979 // Set alignment to 1 to prevent padding between two contributions from input
5980 // sections after linking.
5981 GV->setAlignment(Align(1));
5982 UsedArray.push_back(
5984 if (llvm::GlobalVariable *Old =
5985 M.getGlobalVariable("llvm.embedded.module", true)) {
5986 assert(Old->hasZeroLiveUses() &&
5987 "llvm.embedded.module can only be used once in llvm.compiler.used");
5988 GV->takeName(Old);
5989 Old->eraseFromParent();
5990 } else {
5991 GV->setName("llvm.embedded.module");
5992 }
5993
5994 // Skip if only bitcode needs to be embedded.
5995 if (EmbedCmdline) {
5996 // Embed command-line options.
5997 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
5998 CmdArgs.size());
5999 llvm::Constant *CmdConstant =
6000 llvm::ConstantDataArray::get(M.getContext(), CmdData);
6001 GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
6003 CmdConstant);
6005 GV->setAlignment(Align(1));
6006 UsedArray.push_back(
6008 if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
6009 assert(Old->hasZeroLiveUses() &&
6010 "llvm.cmdline can only be used once in llvm.compiler.used");
6011 GV->takeName(Old);
6012 Old->eraseFromParent();
6013 } else {
6014 GV->setName("llvm.cmdline");
6015 }
6016 }
6017
6018 if (UsedArray.empty())
6019 return;
6020
6021 // Recreate llvm.compiler.used.
6022 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
6023 auto *NewUsed = new GlobalVariable(
6025 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
6026 NewUsed->setSection("llvm.metadata");
6027}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void writeDIMacro(raw_ostream &Out, const DIMacro *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariableExpression(raw_ostream &Out, const DIGlobalVariableExpression *N, AsmWriterContext &WriterCtx)
static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, AsmWriterContext &WriterCtx)
static void writeDIFixedPointType(raw_ostream &Out, const DIFixedPointType *N, AsmWriterContext &WriterCtx)
static void writeDISubrangeType(raw_ostream &Out, const DISubrangeType *N, AsmWriterContext &WriterCtx)
static void writeDIStringType(raw_ostream &Out, const DIStringType *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, AsmWriterContext &WriterCtx)
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, AsmWriterContext &WriterCtx)
static void writeDIModule(raw_ostream &Out, const DIModule *N, AsmWriterContext &WriterCtx)
static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &)
static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, AsmWriterContext &WriterCtx)
static void writeDILabel(raw_ostream &Out, const DILabel *N, AsmWriterContext &WriterCtx)
static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, AsmWriterContext &WriterCtx)
static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, AsmWriterContext &WriterCtx)
static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, AsmWriterContext &WriterCtx)
static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, AsmWriterContext &WriterCtx)
static void writeDILocation(raw_ostream &Out, const DILocation *DL, AsmWriterContext &WriterCtx)
static void writeDINamespace(raw_ostream &Out, const DINamespace *N, AsmWriterContext &WriterCtx)
static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, AsmWriterContext &WriterCtx)
static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, AsmWriterContext &WriterCtx)
static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, AsmWriterContext &WriterCtx)
static void writeDITemplateTypeParameter(raw_ostream &Out, const DITemplateTypeParameter *N, AsmWriterContext &WriterCtx)
static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, AsmWriterContext &WriterCtx)
static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N, AsmWriterContext &WriterCtx)
static void writeDISubrange(raw_ostream &Out, const DISubrange *N, AsmWriterContext &WriterCtx)
static void writeDILexicalBlockFile(raw_ostream &Out, const DILexicalBlockFile *N, AsmWriterContext &WriterCtx)
static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, AsmWriterContext &)
static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, AsmWriterContext &WriterCtx)
static void writeDIExpression(raw_ostream &Out, const DIExpression *N, AsmWriterContext &WriterCtx)
static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL, AsmWriterContext &WriterCtx)
static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, AsmWriterContext &WriterCtx)
static void writeDIArgList(raw_ostream &Out, const DIArgList *N, AsmWriterContext &WriterCtx, bool FromValue=false)
static void writeDITemplateValueParameter(raw_ostream &Out, const DITemplateValueParameter *N, AsmWriterContext &WriterCtx)
static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, AsmWriterContext &WriterCtx)
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void writeFunctionHeapProfileRecords(BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev, unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule, std::function< unsigned(const ValueInfo &VI)> GetValueID, std::function< unsigned(unsigned)> GetStackIndex, bool WriteContextSizeInfoIndex, DenseMap< CallStackId, LinearCallStackId > &CallStackPos, CallStackId &CallStackCount)
static unsigned serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta)
static void writeTypeIdCompatibleVtableSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdCompatibleVtableInfo &Summary, ValueEnumerator &VE)
static void getReferencedTypeIds(FunctionSummary *FS, std::set< GlobalValue::GUID > &ReferencedTypeIds)
Collect type IDs from type tests used by function.
static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind)
static void collectMemProfCallStacks(FunctionSummary *FS, std::function< LinearFrameId(unsigned)> GetStackIndex, MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &CallStacks)
static unsigned getEncodedUnaryOpcode(unsigned Opcode)
static void emitSignedInt64(SmallVectorImpl< uint64_t > &Vals, uint64_t V)
StringEncoding
@ SE_Char6
@ SE_Fixed7
@ SE_Fixed8
static unsigned getEncodedVisibility(const GlobalValue &GV)
static uint64_t getOptimizationFlags(const Value *V)
static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage)
static cl::opt< bool > PreserveBitcodeUseListOrder("preserve-bc-uselistorder", cl::Hidden, cl::init(true), cl::desc("Preserve use-list order when writing LLVM bitcode."))
static unsigned getEncodedThreadLocalMode(const GlobalValue &GV)
static DenseMap< CallStackId, LinearCallStackId > writeMemoryProfileRadixTree(MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &&CallStacks, BitstreamWriter &Stream, unsigned RadixAbbrev)
static void writeIdentificationBlock(BitstreamWriter &Stream)
Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the current llvm version,...
static unsigned getEncodedCastOpcode(unsigned Opcode)
static cl::opt< 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)
static unsigned getEncodedComdatSelectionKind(const Comdat &C)
static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags, bool ImportAsDecl=false)
static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl< char > &Buffer, const Triple &TT)
If generating a bc file on darwin, we have to emit a header and trailer to make it compatible with th...
static void writeBitcodeHeader(BitstreamWriter &Stream)
Helper to write the header common to all bitcode files.
static void writeWholeProgramDevirtResolutionByArg(SmallVector< uint64_t, 64 > &NameVals, const std::vector< uint64_t > &args, const WholeProgramDevirtResolution::ByArg &ByArg)
static void emitConstantRange(SmallVectorImpl< uint64_t > &Record, const ConstantRange &CR, bool EmitBitWidth)
static StringEncoding getStringEncoding(StringRef Str)
Determine the encoding to use for the given string name and length.
static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags)
static const char * getSectionNameForCommandline(const Triple &T)
static cl::opt< unsigned > IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25), cl::desc("Number of metadatas above which we emit an index " "to enable lazy-loading"))
static void writeTypeIdSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdSummary &Summary)
static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream, FunctionSummary *FS, Fn GetValueID)
Write the function type metadata related records that need to appear before a function summary entry ...
static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI)
static void emitWideAPInt(SmallVectorImpl< uint64_t > &Vals, const APInt &A)
static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, StringRef Str, unsigned AbbrevToUse)
static unsigned getEncodedRMWOperation(const AtomicRMWInst &I)
static void writeWholeProgramDevirtResolution(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, uint64_t Id, const WholeProgramDevirtResolution &Wpd)
static unsigned getEncodedDLLStorageClass(const GlobalValue &GV)
static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl< char > &Buffer, uint32_t &Position)
MetadataAbbrev
@ LastPlusOne
static const char * getSectionNameForBitcode(const Triple &T)
static cl::opt< bool > CombinedIndexMemProfContext("combined-index-memprof-context", cl::Hidden, cl::init(true), cl::desc(""))
static unsigned getEncodedBinaryOpcode(unsigned Opcode)
static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Hexagon Common GEP
#define _
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static cl::opt< LTOBitcodeEmbedding > EmbedBitcode("lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed), cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none", "Do not embed"), clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized", "Embed after all optimization passes"), clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized, "post-merge-pre-opt", "Embed post merge, but before optimizations")), cl::desc("Embed LLVM bitcode in object files produced by LTO"))
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
Machine Check Debug Module
This file contains the declarations for metadata subclasses.
#define T
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
nvptx lower args
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
if(PassOpts->AAPipeline)
This file contains some templates that are useful if you are working with the STL at all.
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:83
Class for arbitrary precision integers.
Definition APInt.h:78
unsigned getActiveWords() const
Compute the number of active words in the value of this APInt.
Definition APInt.h:1541
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition APInt.h:576
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1585
const GlobalValueSummary & getAliasee() const
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
unsigned getAddressSpace() const
Return the address space for the allocation.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
an instruction that atomically reads a memory location, combines it with another value,...
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
bool hasAttributes() const
Return true if attributes exists in this set.
Definition Attributes.h:477
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:124
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
Definition Attributes.h:131
@ None
No attributes have been set.
Definition Attributes.h:126
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
Definition Attributes.h:130
@ EndAttrKinds
Sentinel value useful for loops.
Definition Attributes.h:129
BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
Definition BitCodes.h:34
static bool isChar6(char C)
isChar6 - Return true if this character is legal in the Char6 encoding.
Definition BitCodes.h:88
LLVM_ABI 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...
LLVM_ABI void writeIndex(const ModuleSummaryIndex *Index, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex, const GVSummaryPtrSet *DecSummaries)
LLVM_ABI void copyStrtab(StringRef Strtab)
Copy the string table for another module into this bitcode file.
LLVM_ABI void writeStrtab()
Write the bitcode file's string table.
LLVM_ABI void writeSymtab()
Attempt to write a symbol table to the bitcode file.
LLVM_ABI 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.
LLVM_ABI 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.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
BasicBlock * getIndirectDest(unsigned i) const
BasicBlock * getDefaultDest() const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
bool isNoTailCall() const
bool isTailCall() const
bool isMustTailCall() const
auto getNamesForGUID(GlobalValue::GUID GUID) const
get the name(s) associated with a given ThinLTO GUID.
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
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:872
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
This class represents a range of values.
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.
This is an important base class in LLVM.
Definition Constant.h:43
DebugLoc getDebugLoc() const
LLVM_ABI DIAssignID * getAssignID() const
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:174
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:221
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:216
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:286
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
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.
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:284
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
static bool isLocalLinkage(LinkageTypes Linkage)
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
ThreadLocalMode getThreadLocalMode() const
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ DLLImportStorageClass
Function to be imported from DLL.
Definition GlobalValue.h:76
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
UnnamedAddr getUnnamedAddr() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
DLLStorageClassTypes getDLLStorageClass() const
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
idx_iterator idx_end() const
idx_iterator idx_begin() const
bool isCast() const
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.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
bool empty() const
Definition MapVector.h:79
size_t getBufferSize() const
const char * getBufferStart() const
const char * getBufferEnd() const
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:67
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...
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
Definition SHA1.cpp:208
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
Definition SHA1.cpp:288
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void resize(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
const ValueTy & getValue() const
StringRef getKey() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
iterator begin() const
Definition StringRef.h:114
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
iterator end() const
Definition StringRef.h:116
Utility for building string tables with deduplicated suffixes.
LLVM_ABI size_t add(CachedHashStringRef S, uint8_t Priority=0)
Add a string to the builder.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
@ UnknownObjectFormat
Definition Triple.h:332
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isX86_FP80Ty() const
Return true if this is x86 long double.
Definition Type.h:161
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:147
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition Type.h:167
bool isFP128Ty() const
Return true if this is 'fp128'.
Definition Type.h:164
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
Value * getValue() const
Definition Metadata.h:499
std::vector< std::pair< const Value *, unsigned > > ValueList
unsigned getTypeID(Type *T) const
unsigned getMetadataID(const Metadata *MD) const
UseListOrderStack UseListOrders
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
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:393
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:399
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:212
void build(llvm::MapVector< CallStackId, llvm::SmallVector< FrameIdTy > > &&MemProfCallStackData, const llvm::DenseMap< FrameIdTy, LinearFrameId > *MemProfFrameIndexes, llvm::DenseMap< FrameIdTy, FrameStat > &FrameHistogram)
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & write(unsigned char C)
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
CallInst * Call
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.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:50
@ TYPE_CODE_TARGET_TYPE
@ TYPE_CODE_STRUCT_ANON
@ TYPE_CODE_STRUCT_NAME
@ TYPE_CODE_OPAQUE_POINTER
@ TYPE_CODE_STRUCT_NAMED
@ METADATA_COMMON_BLOCK
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_INDEX_OFFSET
@ METADATA_LEXICAL_BLOCK
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_OBJC_PROPERTY
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPILE_UNIT
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_DERIVED_TYPE
@ METADATA_SUBRANGE_TYPE
@ METADATA_TEMPLATE_TYPE
@ METADATA_GLOBAL_VAR_EXPR
@ METADATA_DISTINCT_NODE
@ METADATA_GENERIC_DEBUG
GlobalValueSummarySymtabCodes
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_CFI_FUNCTION_DECLS
@ FS_COMBINED_CALLSITE_INFO
@ FS_COMBINED_ALLOC_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ BITCODE_CURRENT_EPOCH
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_BLOCKADDRESS
@ CST_CODE_NO_CFI_VALUE
@ CST_CODE_CE_SHUFVEC_EX
@ CST_CODE_CE_EXTRACTELT
@ CST_CODE_CE_SHUFFLEVEC
@ CST_CODE_WIDE_INTEGER
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_CE_INSERTELT
@ CST_CODE_CE_GEP_WITH_INRANGE
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_SWIFT_ERROR
@ ATTR_KIND_NO_CALLBACK
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_INLINE_HINT
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_MUSTPROGRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_INITIALIZES
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_SKIP_PROFILE
@ ATTR_KIND_ELEMENTTYPE
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NO_DUPLICATE
@ ATTR_KIND_ALLOC_ALIGN
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_HYBRID_PATCHABLE
@ ATTR_KIND_NO_RED_ZONE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_VSCALE_RANGE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_SPECULATABLE
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ ATTR_KIND_PREALLOCATED
@ ATTR_KIND_SWIFT_ASYNC
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ METADATA_KIND_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ METADATA_ATTACHMENT_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ MODULE_STRTAB_BLOCK_ID
@ VALUE_SYMTAB_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ MODULE_CODE_VERSION
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_DATALAYOUT
@ MODULE_CODE_GLOBALVAR
@ MODULE_CODE_VSTOFFSET
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_RESUME
@ FUNC_CODE_INST_CALLBR
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_VSELECT
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_INST_INVOKE
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_SWITCH
@ FUNC_CODE_INST_ALLOCA
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_FREEZE
@ FUNC_CODE_INST_CMPXCHG
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ FIRST_APPLICATION_ABBREV
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Definition Dwarf.h:51
LLVM_ABI 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:349
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
Definition Transport.h:139
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:683
LLVM_ABI bool metadataIncludesAllContextSizeInfo()
Whether the alloc memeprof metadata will include context size info for all MIBs.
template LLVM_ABI llvm::DenseMap< LinearFrameId, FrameStat > computeFrameHistogram< LinearFrameId >(llvm::MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &MemProfCallStackData)
LLVM_ABI bool metadataMayIncludeContextSizeInfo()
Whether the alloc memprof metadata may include context size info for some MIBs (but possibly not all)...
uint32_t LinearFrameId
Definition MemProf.h:238
uint64_t CallStackId
Definition MemProf.h:352
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:388
void write32le(void *P, uint32_t V)
Definition Endian.h:475
uint32_t read32be(const void *P)
Definition Endian.h:441
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
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:344
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
StringMapEntry< Value * > ValueName
Definition Value.h:56
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1668
std::unordered_set< GlobalValueSummary * > GVSummaryPtrSet
A set of global value summary pointers.
unsigned encode(MaybeAlign A)
Returns a representation of the alignment that encodes undefined as 0.
Definition Alignment.h:206
LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2553
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the given raw output...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
@ BWH_HeaderSize
FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2207
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
LLVM_ABI 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:1745
FunctionAddr VTableAddr uintptr_t uintptr_t Version
Definition InstrProf.h:334
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:221
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1884
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
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,...
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Definition DWP.cpp:721
LLVM_ABI 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:898
#define N
#define NC
Definition regutils.h:42
#define NDEBUG
Definition regutils.h:48
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static void set(StorageType &Packed, typename Bitfield::Type Value)
Sets the typed value in the provided Packed value.
Definition Bitfields.h:223
Class to accumulate and hold information about a callee.
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
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,...