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 } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1816 if (NNI->hasNonNeg())
1817 Flags |= 1 << bitc::PNNI_NON_NEG;
1818 } else if (const auto *TI = dyn_cast<TruncInst>(V)) {
1819 if (TI->hasNoSignedWrap())
1820 Flags |= 1 << bitc::TIO_NO_SIGNED_WRAP;
1821 if (TI->hasNoUnsignedWrap())
1822 Flags |= 1 << bitc::TIO_NO_UNSIGNED_WRAP;
1823 } else if (const auto *GEP = dyn_cast<GEPOperator>(V)) {
1824 if (GEP->isInBounds())
1825 Flags |= 1 << bitc::GEP_INBOUNDS;
1826 if (GEP->hasNoUnsignedSignedWrap())
1827 Flags |= 1 << bitc::GEP_NUSW;
1828 if (GEP->hasNoUnsignedWrap())
1829 Flags |= 1 << bitc::GEP_NUW;
1830 } else if (const auto *ICmp = dyn_cast<ICmpInst>(V)) {
1831 if (ICmp->hasSameSign())
1832 Flags |= 1 << bitc::ICMP_SAME_SIGN;
1833 }
1834
1835 return Flags;
1836}
1837
1838void ModuleBitcodeWriter::writeValueAsMetadata(
1839 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1840 // Mimic an MDNode with a value as one operand.
1841 Value *V = MD->getValue();
1842 Record.push_back(VE.getTypeID(V->getType()));
1843 Record.push_back(VE.getValueID(V));
1844 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1845 Record.clear();
1846}
1847
1848void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1849 SmallVectorImpl<uint64_t> &Record,
1850 unsigned Abbrev) {
1851 for (const MDOperand &MDO : N->operands()) {
1852 Metadata *MD = MDO;
1853 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1854 "Unexpected function-local metadata");
1855 Record.push_back(VE.getMetadataOrNullID(MD));
1856 }
1857 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1859 Record, Abbrev);
1860 Record.clear();
1861}
1862
1863unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1864 // Assume the column is usually under 128, and always output the inlined-at
1865 // location (it's never more expensive than building an array size 1).
1866 auto Abbv = std::make_shared<BitCodeAbbrev>();
1867 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1868 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isDistinct
1869 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // line
1870 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // column
1871 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // scope
1872 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // inlinedAt
1873 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isImplicitCode
1874 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // atomGroup
1875 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // atomRank
1876 return Stream.EmitAbbrev(std::move(Abbv));
1877}
1878
1879void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1880 SmallVectorImpl<uint64_t> &Record,
1881 unsigned &Abbrev) {
1882 if (!Abbrev)
1883 Abbrev = createDILocationAbbrev();
1884
1885 Record.push_back(N->isDistinct());
1886 Record.push_back(N->getLine());
1887 Record.push_back(N->getColumn());
1888 Record.push_back(VE.getMetadataID(N->getScope()));
1889 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1890 Record.push_back(N->isImplicitCode());
1891 Record.push_back(N->getAtomGroup());
1892 Record.push_back(N->getAtomRank());
1893 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1894 Record.clear();
1895}
1896
1897unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1898 // Assume the column is usually under 128, and always output the inlined-at
1899 // location (it's never more expensive than building an array size 1).
1900 auto Abbv = std::make_shared<BitCodeAbbrev>();
1901 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1902 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1903 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1904 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1905 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1906 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1907 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1908 return Stream.EmitAbbrev(std::move(Abbv));
1909}
1910
1911void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1912 SmallVectorImpl<uint64_t> &Record,
1913 unsigned &Abbrev) {
1914 if (!Abbrev)
1915 Abbrev = createGenericDINodeAbbrev();
1916
1917 Record.push_back(N->isDistinct());
1918 Record.push_back(N->getTag());
1919 Record.push_back(0); // Per-tag version field; unused for now.
1920
1921 for (auto &I : N->operands())
1922 Record.push_back(VE.getMetadataOrNullID(I));
1923
1924 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1925 Record.clear();
1926}
1927
1928void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1929 SmallVectorImpl<uint64_t> &Record,
1930 unsigned Abbrev) {
1931 const uint64_t Version = 2 << 1;
1932 Record.push_back((uint64_t)N->isDistinct() | Version);
1933 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1934 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1935 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1936 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1937
1938 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1939 Record.clear();
1940}
1941
1942void ModuleBitcodeWriter::writeDIGenericSubrange(
1943 const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record,
1944 unsigned Abbrev) {
1945 Record.push_back((uint64_t)N->isDistinct());
1946 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1947 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1948 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1949 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1950
1951 Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);
1952 Record.clear();
1953}
1954
1955void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1956 SmallVectorImpl<uint64_t> &Record,
1957 unsigned Abbrev) {
1958 const uint64_t IsBigInt = 1 << 2;
1959 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
1960 Record.push_back(N->getValue().getBitWidth());
1961 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1962 emitWideAPInt(Record, N->getValue());
1963
1964 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1965 Record.clear();
1966}
1967
1968void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1969 SmallVectorImpl<uint64_t> &Record,
1970 unsigned Abbrev) {
1971 const unsigned SizeIsMetadata = 0x2;
1972 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
1973 Record.push_back(N->getTag());
1974 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1975 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
1976 Record.push_back(N->getAlignInBits());
1977 Record.push_back(N->getEncoding());
1978 Record.push_back(N->getFlags());
1979 Record.push_back(N->getNumExtraInhabitants());
1980 Record.push_back(N->getDataSizeInBits());
1981 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1982 Record.push_back(N->getLine());
1983 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1984
1985 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1986 Record.clear();
1987}
1988
1989void ModuleBitcodeWriter::writeDIFixedPointType(
1990 const DIFixedPointType *N, SmallVectorImpl<uint64_t> &Record,
1991 unsigned Abbrev) {
1992 const unsigned SizeIsMetadata = 0x2;
1993 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
1994 Record.push_back(N->getTag());
1995 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1996 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
1997 Record.push_back(N->getAlignInBits());
1998 Record.push_back(N->getEncoding());
1999 Record.push_back(N->getFlags());
2000 Record.push_back(N->getKind());
2001 Record.push_back(N->getFactorRaw());
2002
2003 auto WriteWideInt = [&](const APInt &Value) {
2004 // Write an encoded word that holds the number of active words and
2005 // the number of bits.
2006 uint64_t NumWords = Value.getActiveWords();
2007 uint64_t Encoded = (NumWords << 32) | Value.getBitWidth();
2008 Record.push_back(Encoded);
2009 emitWideAPInt(Record, Value);
2010 };
2011
2012 WriteWideInt(N->getNumeratorRaw());
2013 WriteWideInt(N->getDenominatorRaw());
2014
2015 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2016 Record.push_back(N->getLine());
2017 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2018
2019 Stream.EmitRecord(bitc::METADATA_FIXED_POINT_TYPE, Record, Abbrev);
2020 Record.clear();
2021}
2022
2023void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
2024 SmallVectorImpl<uint64_t> &Record,
2025 unsigned Abbrev) {
2026 const unsigned SizeIsMetadata = 0x2;
2027 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2028 Record.push_back(N->getTag());
2029 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2030 Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
2031 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
2032 Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
2033 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2034 Record.push_back(N->getAlignInBits());
2035 Record.push_back(N->getEncoding());
2036
2037 Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
2038 Record.clear();
2039}
2040
2041void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
2042 SmallVectorImpl<uint64_t> &Record,
2043 unsigned Abbrev) {
2044 const unsigned SizeIsMetadata = 0x2;
2045 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2046 Record.push_back(N->getTag());
2047 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2048 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2049 Record.push_back(N->getLine());
2050 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2051 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2052 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2053 Record.push_back(N->getAlignInBits());
2054 Record.push_back(VE.getMetadataOrNullID(N->getRawOffsetInBits()));
2055 Record.push_back(N->getFlags());
2056 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
2057
2058 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
2059 // that there is no DWARF address space associated with DIDerivedType.
2060 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
2061 Record.push_back(*DWARFAddressSpace + 1);
2062 else
2063 Record.push_back(0);
2064
2065 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2066
2067 if (auto PtrAuthData = N->getPtrAuthData())
2068 Record.push_back(PtrAuthData->RawData);
2069 else
2070 Record.push_back(0);
2071
2072 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
2073 Record.clear();
2074}
2075
2076void ModuleBitcodeWriter::writeDISubrangeType(const DISubrangeType *N,
2077 SmallVectorImpl<uint64_t> &Record,
2078 unsigned Abbrev) {
2079 const unsigned SizeIsMetadata = 0x2;
2080 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2081 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2082 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2083 Record.push_back(N->getLine());
2084 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2085 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2086 Record.push_back(N->getAlignInBits());
2087 Record.push_back(N->getFlags());
2088 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2089 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
2090 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
2091 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
2092 Record.push_back(VE.getMetadataOrNullID(N->getRawBias()));
2093
2094 Stream.EmitRecord(bitc::METADATA_SUBRANGE_TYPE, Record, Abbrev);
2095 Record.clear();
2096}
2097
2098void ModuleBitcodeWriter::writeDICompositeType(
2099 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
2100 unsigned Abbrev) {
2101 const unsigned IsNotUsedInOldTypeRef = 0x2;
2102 const unsigned SizeIsMetadata = 0x4;
2103 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2104 (unsigned)N->isDistinct());
2105 Record.push_back(N->getTag());
2106 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2107 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2108 Record.push_back(N->getLine());
2109 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2110 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2111 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2112 Record.push_back(N->getAlignInBits());
2113 Record.push_back(VE.getMetadataOrNullID(N->getRawOffsetInBits()));
2114 Record.push_back(N->getFlags());
2115 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2116 Record.push_back(N->getRuntimeLang());
2117 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
2118 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2119 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
2120 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
2121 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
2122 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
2123 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
2124 Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
2125 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2126 Record.push_back(N->getNumExtraInhabitants());
2127 Record.push_back(VE.getMetadataOrNullID(N->getRawSpecification()));
2128 Record.push_back(
2129 N->getEnumKind().value_or(dwarf::DW_APPLE_ENUM_KIND_invalid));
2130 Record.push_back(VE.getMetadataOrNullID(N->getRawBitStride()));
2131
2132 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
2133 Record.clear();
2134}
2135
2136void ModuleBitcodeWriter::writeDISubroutineType(
2137 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
2138 unsigned Abbrev) {
2139 const unsigned HasNoOldTypeRefs = 0x2;
2140 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
2141 Record.push_back(N->getFlags());
2142 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
2143 Record.push_back(N->getCC());
2144
2145 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
2146 Record.clear();
2147}
2148
2149void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
2150 SmallVectorImpl<uint64_t> &Record,
2151 unsigned Abbrev) {
2152 Record.push_back(N->isDistinct());
2153 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
2154 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
2155 if (N->getRawChecksum()) {
2156 Record.push_back(N->getRawChecksum()->Kind);
2157 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
2158 } else {
2159 // Maintain backwards compatibility with the old internal representation of
2160 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
2161 Record.push_back(0);
2162 Record.push_back(VE.getMetadataOrNullID(nullptr));
2163 }
2164 auto Source = N->getRawSource();
2165 if (Source)
2166 Record.push_back(VE.getMetadataOrNullID(Source));
2167
2168 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
2169 Record.clear();
2170}
2171
2172void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
2173 SmallVectorImpl<uint64_t> &Record,
2174 unsigned Abbrev) {
2175 assert(N->isDistinct() && "Expected distinct compile units");
2176 Record.push_back(/* IsDistinct */ true);
2177
2178 auto Lang = N->getSourceLanguage();
2179 Record.push_back(Lang.getName());
2180 // Set bit so the MetadataLoader can distniguish between versioned and
2181 // unversioned names.
2182 if (Lang.hasVersionedName())
2183 Record.back() ^= (uint64_t(1) << 63);
2184
2185 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2186 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
2187 Record.push_back(N->isOptimized());
2188 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
2189 Record.push_back(N->getRuntimeVersion());
2190 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
2191 Record.push_back(N->getEmissionKind());
2192 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
2193 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
2194 Record.push_back(/* subprograms */ 0);
2195 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
2196 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
2197 Record.push_back(N->getDWOId());
2198 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
2199 Record.push_back(N->getSplitDebugInlining());
2200 Record.push_back(N->getDebugInfoForProfiling());
2201 Record.push_back((unsigned)N->getNameTableKind());
2202 Record.push_back(N->getRangesBaseAddress());
2203 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
2204 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
2205 Record.push_back(Lang.hasVersionedName() ? Lang.getVersion() : 0);
2206 Record.push_back(Lang.getDialect());
2207
2208 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
2209 Record.clear();
2210}
2211
2212void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
2213 SmallVectorImpl<uint64_t> &Record,
2214 unsigned Abbrev) {
2215 const uint64_t HasUnitFlag = 1 << 1;
2216 const uint64_t HasSPFlagsFlag = 1 << 2;
2217 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2218 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2219 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2220 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2221 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2222 Record.push_back(N->getLine());
2223 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2224 Record.push_back(N->getScopeLine());
2225 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
2226 Record.push_back(N->getSPFlags());
2227 Record.push_back(N->getVirtualIndex());
2228 Record.push_back(N->getFlags());
2229 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
2230 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2231 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
2232 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
2233 Record.push_back(N->getThisAdjustment());
2234 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
2235 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2236 Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
2237 Record.push_back(N->getKeyInstructionsEnabled());
2238
2239 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
2240 Record.clear();
2241}
2242
2243void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
2244 SmallVectorImpl<uint64_t> &Record,
2245 unsigned Abbrev) {
2246 Record.push_back(N->isDistinct());
2247 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2248 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2249 Record.push_back(N->getLine());
2250 Record.push_back(N->getColumn());
2251
2252 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
2253 Record.clear();
2254}
2255
2256void ModuleBitcodeWriter::writeDILexicalBlockFile(
2257 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
2258 unsigned Abbrev) {
2259 Record.push_back(N->isDistinct());
2260 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2261 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2262 Record.push_back(N->getDiscriminator());
2263
2264 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
2265 Record.clear();
2266}
2267
2268void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
2269 SmallVectorImpl<uint64_t> &Record,
2270 unsigned Abbrev) {
2271 Record.push_back(N->isDistinct());
2272 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2273 Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
2274 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2275 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2276 Record.push_back(N->getLineNo());
2277
2278 Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
2279 Record.clear();
2280}
2281
2282void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
2283 SmallVectorImpl<uint64_t> &Record,
2284 unsigned Abbrev) {
2285 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
2286 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2287 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2288
2289 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
2290 Record.clear();
2291}
2292
2293void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
2294 SmallVectorImpl<uint64_t> &Record,
2295 unsigned Abbrev) {
2296 Record.push_back(N->isDistinct());
2297 Record.push_back(N->getMacinfoType());
2298 Record.push_back(N->getLine());
2299 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2300 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
2301
2302 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
2303 Record.clear();
2304}
2305
2306void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
2307 SmallVectorImpl<uint64_t> &Record,
2308 unsigned Abbrev) {
2309 Record.push_back(N->isDistinct());
2310 Record.push_back(N->getMacinfoType());
2311 Record.push_back(N->getLine());
2312 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2313 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2314
2315 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
2316 Record.clear();
2317}
2318
2319void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
2320 SmallVectorImpl<uint64_t> &Record) {
2321 Record.reserve(N->getArgs().size());
2322 for (ValueAsMetadata *MD : N->getArgs())
2323 Record.push_back(VE.getMetadataID(MD));
2324
2325 Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record);
2326 Record.clear();
2327}
2328
2329void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
2330 SmallVectorImpl<uint64_t> &Record,
2331 unsigned Abbrev) {
2332 Record.push_back(N->isDistinct());
2333 for (auto &I : N->operands())
2334 Record.push_back(VE.getMetadataOrNullID(I));
2335 Record.push_back(N->getLineNo());
2336 Record.push_back(N->getIsDecl());
2337
2338 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
2339 Record.clear();
2340}
2341
2342void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
2343 SmallVectorImpl<uint64_t> &Record,
2344 unsigned Abbrev) {
2345 // There are no arguments for this metadata type.
2346 Record.push_back(N->isDistinct());
2347 Stream.EmitRecord(bitc::METADATA_ASSIGN_ID, Record, Abbrev);
2348 Record.clear();
2349}
2350
2351void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2352 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
2353 unsigned Abbrev) {
2354 Record.push_back(N->isDistinct());
2355 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2356 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2357 Record.push_back(N->isDefault());
2358
2359 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
2360 Record.clear();
2361}
2362
2363void ModuleBitcodeWriter::writeDITemplateValueParameter(
2364 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
2365 unsigned Abbrev) {
2366 Record.push_back(N->isDistinct());
2367 Record.push_back(N->getTag());
2368 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2369 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2370 Record.push_back(N->isDefault());
2371 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
2372
2373 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
2374 Record.clear();
2375}
2376
2377void ModuleBitcodeWriter::writeDIGlobalVariable(
2378 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
2379 unsigned Abbrev) {
2380 const uint64_t Version = 2 << 1;
2381 Record.push_back((uint64_t)N->isDistinct() | Version);
2382 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2383 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2384 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2385 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2386 Record.push_back(N->getLine());
2387 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2388 Record.push_back(N->isLocalToUnit());
2389 Record.push_back(N->isDefinition());
2390 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
2391 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
2392 Record.push_back(N->getAlignInBits());
2393 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2394
2395 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
2396 Record.clear();
2397}
2398
2399void ModuleBitcodeWriter::writeDILocalVariable(
2400 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
2401 unsigned Abbrev) {
2402 // In order to support all possible bitcode formats in BitcodeReader we need
2403 // to distinguish the following cases:
2404 // 1) Record has no artificial tag (Record[1]),
2405 // has no obsolete inlinedAt field (Record[9]).
2406 // In this case Record size will be 8, HasAlignment flag is false.
2407 // 2) Record has artificial tag (Record[1]),
2408 // has no obsolete inlignedAt field (Record[9]).
2409 // In this case Record size will be 9, HasAlignment flag is false.
2410 // 3) Record has both artificial tag (Record[1]) and
2411 // obsolete inlignedAt field (Record[9]).
2412 // In this case Record size will be 10, HasAlignment flag is false.
2413 // 4) Record has neither artificial tag, nor inlignedAt field, but
2414 // HasAlignment flag is true and Record[8] contains alignment value.
2415 const uint64_t HasAlignmentFlag = 1 << 1;
2416 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2417 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2418 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2419 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2420 Record.push_back(N->getLine());
2421 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2422 Record.push_back(N->getArg());
2423 Record.push_back(N->getFlags());
2424 Record.push_back(N->getAlignInBits());
2425 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2426
2427 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
2428 Record.clear();
2429}
2430
2431void ModuleBitcodeWriter::writeDILabel(
2432 const DILabel *N, SmallVectorImpl<uint64_t> &Record,
2433 unsigned Abbrev) {
2434 uint64_t IsArtificialFlag = uint64_t(N->isArtificial()) << 1;
2435 Record.push_back((uint64_t)N->isDistinct() | IsArtificialFlag);
2436 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2437 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2438 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2439 Record.push_back(N->getLine());
2440 Record.push_back(N->getColumn());
2441 Record.push_back(N->getCoroSuspendIdx().has_value()
2442 ? (uint64_t)N->getCoroSuspendIdx().value()
2443 : std::numeric_limits<uint64_t>::max());
2444
2445 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2446 Record.clear();
2447}
2448
2449void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
2450 SmallVectorImpl<uint64_t> &Record,
2451 unsigned Abbrev) {
2452 Record.reserve(N->getElements().size() + 1);
2453 const uint64_t Version = 3 << 1;
2454 Record.push_back((uint64_t)N->isDistinct() | Version);
2455 Record.append(N->elements_begin(), N->elements_end());
2456
2457 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
2458 Record.clear();
2459}
2460
2461void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2462 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
2463 unsigned Abbrev) {
2464 Record.push_back(N->isDistinct());
2465 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2466 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2467
2468 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
2469 Record.clear();
2470}
2471
2472void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
2473 SmallVectorImpl<uint64_t> &Record,
2474 unsigned Abbrev) {
2475 Record.push_back(N->isDistinct());
2476 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2477 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2478 Record.push_back(N->getLine());
2479 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2480 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2481 Record.push_back(N->getAttributes());
2482 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2483
2484 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
2485 Record.clear();
2486}
2487
2488void ModuleBitcodeWriter::writeDIImportedEntity(
2489 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
2490 unsigned Abbrev) {
2491 Record.push_back(N->isDistinct());
2492 Record.push_back(N->getTag());
2493 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2494 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2495 Record.push_back(N->getLine());
2496 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2497 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2498 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2499
2500 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
2501 Record.clear();
2502}
2503
2504unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2505 auto Abbv = std::make_shared<BitCodeAbbrev>();
2506 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
2507 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2508 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2509 return Stream.EmitAbbrev(std::move(Abbv));
2510}
2511
2512void ModuleBitcodeWriter::writeNamedMetadata(
2513 SmallVectorImpl<uint64_t> &Record) {
2514 if (M.named_metadata_empty())
2515 return;
2516
2517 unsigned Abbrev = createNamedMetadataAbbrev();
2518 for (const NamedMDNode &NMD : M.named_metadata()) {
2519 // Write name.
2520 StringRef Str = NMD.getName();
2521 Record.append(Str.bytes_begin(), Str.bytes_end());
2522 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2523 Record.clear();
2524
2525 // Write named metadata operands.
2526 for (const MDNode *N : NMD.operands())
2527 Record.push_back(VE.getMetadataID(N));
2528 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
2529 Record.clear();
2530 }
2531}
2532
2533unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2534 auto Abbv = std::make_shared<BitCodeAbbrev>();
2535 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
2536 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2537 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2538 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2539 return Stream.EmitAbbrev(std::move(Abbv));
2540}
2541
2542/// Write out a record for MDString.
2543///
2544/// All the metadata strings in a metadata block are emitted in a single
2545/// record. The sizes and strings themselves are shoved into a blob.
2546void ModuleBitcodeWriter::writeMetadataStrings(
2547 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
2548 if (Strings.empty())
2549 return;
2550
2551 // Start the record with the number of strings.
2552 Record.push_back(bitc::METADATA_STRINGS);
2553 Record.push_back(Strings.size());
2554
2555 // Emit the sizes of the strings in the blob.
2556 SmallString<256> Blob;
2557 {
2558 BitstreamWriter W(Blob);
2559 for (const Metadata *MD : Strings)
2560 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2561 W.FlushToWord();
2562 }
2563
2564 // Add the offset to the strings to the record.
2565 Record.push_back(Blob.size());
2566
2567 // Add the strings to the blob.
2568 for (const Metadata *MD : Strings)
2569 Blob.append(cast<MDString>(MD)->getString());
2570
2571 // Emit the final record.
2572 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2573 Record.clear();
2574}
2575
2576// Generates an enum to use as an index in the Abbrev array of Metadata record.
2577enum MetadataAbbrev : unsigned {
2578#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2579#include "llvm/IR/Metadata.def"
2581};
2582
2583void ModuleBitcodeWriter::writeMetadataRecords(
2584 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
2585 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2586 if (MDs.empty())
2587 return;
2588
2589 // Initialize MDNode abbreviations.
2590#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2591#include "llvm/IR/Metadata.def"
2592
2593 for (const Metadata *MD : MDs) {
2594 if (IndexPos)
2595 IndexPos->push_back(Stream.GetCurrentBitNo());
2596 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2597 assert(N->isResolved() && "Expected forward references to be resolved");
2598
2599 switch (N->getMetadataID()) {
2600 default:
2601 llvm_unreachable("Invalid MDNode subclass");
2602#define HANDLE_MDNODE_LEAF(CLASS) \
2603 case Metadata::CLASS##Kind: \
2604 if (MDAbbrevs) \
2605 write##CLASS(cast<CLASS>(N), Record, \
2606 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2607 else \
2608 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2609 continue;
2610#include "llvm/IR/Metadata.def"
2611 }
2612 }
2613 if (auto *AL = dyn_cast<DIArgList>(MD)) {
2615 continue;
2616 }
2617 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2618 }
2619}
2620
2621void ModuleBitcodeWriter::writeModuleMetadata() {
2622 if (!VE.hasMDs() && M.named_metadata_empty())
2623 return;
2624
2626 SmallVector<uint64_t, 64> Record;
2627
2628 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2629 // block and load any metadata.
2630 std::vector<unsigned> MDAbbrevs;
2631
2632 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2633 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2634 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2635 createGenericDINodeAbbrev();
2636
2637 auto Abbv = std::make_shared<BitCodeAbbrev>();
2638 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
2639 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2640 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2641 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2642
2643 Abbv = std::make_shared<BitCodeAbbrev>();
2644 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
2645 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2646 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2647 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2648
2649 // Emit MDStrings together upfront.
2650 writeMetadataStrings(VE.getMDStrings(), Record);
2651
2652 // We only emit an index for the metadata record if we have more than a given
2653 // (naive) threshold of metadatas, otherwise it is not worth it.
2654 if (VE.getNonMDStrings().size() > IndexThreshold) {
2655 // Write a placeholder value in for the offset of the metadata index,
2656 // which is written after the records, so that it can include
2657 // the offset of each entry. The placeholder offset will be
2658 // updated after all records are emitted.
2659 uint64_t Vals[] = {0, 0};
2660 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2661 }
2662
2663 // Compute and save the bit offset to the current position, which will be
2664 // patched when we emit the index later. We can simply subtract the 64-bit
2665 // fixed size from the current bit number to get the location to backpatch.
2666 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2667
2668 // This index will contain the bitpos for each individual record.
2669 std::vector<uint64_t> IndexPos;
2670 IndexPos.reserve(VE.getNonMDStrings().size());
2671
2672 // Write all the records
2673 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2674
2675 if (VE.getNonMDStrings().size() > IndexThreshold) {
2676 // Now that we have emitted all the records we will emit the index. But
2677 // first
2678 // backpatch the forward reference so that the reader can skip the records
2679 // efficiently.
2680 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2681 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2682
2683 // Delta encode the index.
2684 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2685 for (auto &Elt : IndexPos) {
2686 auto EltDelta = Elt - PreviousValue;
2687 PreviousValue = Elt;
2688 Elt = EltDelta;
2689 }
2690 // Emit the index record.
2691 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2692 IndexPos.clear();
2693 }
2694
2695 // Write the named metadata now.
2696 writeNamedMetadata(Record);
2697
2698 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2699 SmallVector<uint64_t, 4> Record;
2700 Record.push_back(VE.getValueID(&GO));
2701 pushGlobalMetadataAttachment(Record, GO);
2703 };
2704 for (const Function &F : M)
2705 if (F.isDeclaration() && F.hasMetadata())
2706 AddDeclAttachedMetadata(F);
2707 for (const GlobalIFunc &GI : M.ifuncs())
2708 if (GI.hasMetadata())
2709 AddDeclAttachedMetadata(GI);
2710 // FIXME: Only store metadata for declarations here, and move data for global
2711 // variable definitions to a separate block (PR28134).
2712 for (const GlobalVariable &GV : M.globals())
2713 if (GV.hasMetadata())
2714 AddDeclAttachedMetadata(GV);
2715
2716 Stream.ExitBlock();
2717}
2718
2719void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2720 if (!VE.hasMDs())
2721 return;
2722
2724 SmallVector<uint64_t, 64> Record;
2725 writeMetadataStrings(VE.getMDStrings(), Record);
2726 writeMetadataRecords(VE.getNonMDStrings(), Record);
2727 Stream.ExitBlock();
2728}
2729
2730void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2731 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2732 // [n x [id, mdnode]]
2734 GO.getAllMetadata(MDs);
2735 for (const auto &I : MDs) {
2736 Record.push_back(I.first);
2737 Record.push_back(VE.getMetadataID(I.second));
2738 }
2739}
2740
2741void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2743
2744 SmallVector<uint64_t, 64> Record;
2745
2746 if (F.hasMetadata()) {
2747 pushGlobalMetadataAttachment(Record, F);
2748 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2749 Record.clear();
2750 }
2751
2752 // Write metadata attachments
2753 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2755 for (const BasicBlock &BB : F)
2756 for (const Instruction &I : BB) {
2757 MDs.clear();
2758 I.getAllMetadataOtherThanDebugLoc(MDs);
2759
2760 // If no metadata, ignore instruction.
2761 if (MDs.empty()) continue;
2762
2763 Record.push_back(VE.getInstructionID(&I));
2764
2765 for (const auto &[ID, MD] : MDs) {
2766 Record.push_back(ID);
2767 Record.push_back(VE.getMetadataID(MD));
2768 }
2769 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2770 Record.clear();
2771 }
2772
2773 Stream.ExitBlock();
2774}
2775
2776void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2777 SmallVector<uint64_t, 64> Record;
2778
2779 // Write metadata kinds
2780 // METADATA_KIND - [n x [id, name]]
2782 M.getMDKindNames(Names);
2783
2784 if (Names.empty()) return;
2785
2787
2788 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2789 Record.push_back(MDKindID);
2790 StringRef KName = Names[MDKindID];
2791 Record.append(KName.begin(), KName.end());
2792
2793 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2794 Record.clear();
2795 }
2796
2797 Stream.ExitBlock();
2798}
2799
2800void ModuleBitcodeWriter::writeOperandBundleTags() {
2801 // Write metadata kinds
2802 //
2803 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2804 //
2805 // OPERAND_BUNDLE_TAG - [strchr x N]
2806
2808 M.getOperandBundleTags(Tags);
2809
2810 if (Tags.empty())
2811 return;
2812
2814
2815 SmallVector<uint64_t, 64> Record;
2816
2817 for (auto Tag : Tags) {
2818 Record.append(Tag.begin(), Tag.end());
2819
2820 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2821 Record.clear();
2822 }
2823
2824 Stream.ExitBlock();
2825}
2826
2827void ModuleBitcodeWriter::writeSyncScopeNames() {
2829 M.getContext().getSyncScopeNames(SSNs);
2830 if (SSNs.empty())
2831 return;
2832
2834
2835 SmallVector<uint64_t, 64> Record;
2836 for (auto SSN : SSNs) {
2837 Record.append(SSN.begin(), SSN.end());
2838 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2839 Record.clear();
2840 }
2841
2842 Stream.ExitBlock();
2843}
2844
2845void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2846 bool isGlobal) {
2847 if (FirstVal == LastVal) return;
2848
2850
2851 unsigned AggregateAbbrev = 0;
2852 unsigned String8Abbrev = 0;
2853 unsigned CString7Abbrev = 0;
2854 unsigned CString6Abbrev = 0;
2855 // If this is a constant pool for the module, emit module-specific abbrevs.
2856 if (isGlobal) {
2857 // Abbrev for CST_CODE_AGGREGATE.
2858 auto Abbv = std::make_shared<BitCodeAbbrev>();
2859 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2860 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2861 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2862 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2863
2864 // Abbrev for CST_CODE_STRING.
2865 Abbv = std::make_shared<BitCodeAbbrev>();
2866 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2867 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2868 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2869 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2870 // Abbrev for CST_CODE_CSTRING.
2871 Abbv = std::make_shared<BitCodeAbbrev>();
2872 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2873 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2874 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2875 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2876 // Abbrev for CST_CODE_CSTRING.
2877 Abbv = std::make_shared<BitCodeAbbrev>();
2878 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2879 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2880 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2881 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2882 }
2883
2884 SmallVector<uint64_t, 64> Record;
2885
2886 const ValueEnumerator::ValueList &Vals = VE.getValues();
2887 Type *LastTy = nullptr;
2888 for (unsigned i = FirstVal; i != LastVal; ++i) {
2889 const Value *V = Vals[i].first;
2890 // If we need to switch types, do so now.
2891 if (V->getType() != LastTy) {
2892 LastTy = V->getType();
2893 Record.push_back(VE.getTypeID(LastTy));
2894 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2895 CONSTANTS_SETTYPE_ABBREV);
2896 Record.clear();
2897 }
2898
2899 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2900 Record.push_back(VE.getTypeID(IA->getFunctionType()));
2901 Record.push_back(
2902 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2903 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2904
2905 // Add the asm string.
2906 StringRef AsmStr = IA->getAsmString();
2907 Record.push_back(AsmStr.size());
2908 Record.append(AsmStr.begin(), AsmStr.end());
2909
2910 // Add the constraint string.
2911 StringRef ConstraintStr = IA->getConstraintString();
2912 Record.push_back(ConstraintStr.size());
2913 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2914 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2915 Record.clear();
2916 continue;
2917 }
2918 const Constant *C = cast<Constant>(V);
2919 unsigned Code = -1U;
2920 unsigned AbbrevToUse = 0;
2921 if (C->isNullValue()) {
2923 } else if (isa<PoisonValue>(C)) {
2925 } else if (isa<UndefValue>(C)) {
2927 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2928 if (IV->getBitWidth() <= 64) {
2929 uint64_t V = IV->getSExtValue();
2930 emitSignedInt64(Record, V);
2932 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2933 } else { // Wide integers, > 64 bits in size.
2934 emitWideAPInt(Record, IV->getValue());
2936 }
2937 } else if (const ConstantByte *BV = dyn_cast<ConstantByte>(C)) {
2938 if (BV->getBitWidth() <= 64) {
2939 uint64_t V = BV->getSExtValue();
2940 emitSignedInt64(Record, V);
2942 AbbrevToUse = CONSTANTS_BYTE_ABBREV;
2943 } else { // Wide bytes, > 64 bits in size.
2944 emitWideAPInt(Record, BV->getValue());
2946 }
2947 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2949 Type *Ty = CFP->getType()->getScalarType();
2950 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2951 Ty->isDoubleTy()) {
2952 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2953 } else if (Ty->isX86_FP80Ty()) {
2954 // api needed to prevent premature destruction
2955 // bits are not in the same order as a normal i80 APInt, compensate.
2956 APInt api = CFP->getValueAPF().bitcastToAPInt();
2957 const uint64_t *p = api.getRawData();
2958 Record.push_back((p[1] << 48) | (p[0] >> 16));
2959 Record.push_back(p[0] & 0xffffLL);
2960 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2961 APInt api = CFP->getValueAPF().bitcastToAPInt();
2962 const uint64_t *p = api.getRawData();
2963 Record.push_back(p[0]);
2964 Record.push_back(p[1]);
2965 } else {
2966 assert(0 && "Unknown FP type!");
2967 }
2968 } else if (isa<ConstantDataSequential>(C) &&
2969 cast<ConstantDataSequential>(C)->isString()) {
2970 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2971 // Emit constant strings specially.
2972 uint64_t NumElts = Str->getNumElements();
2973 // If this is a null-terminated string, use the denser CSTRING encoding.
2974 if (Str->isCString()) {
2976 --NumElts; // Don't encode the null, which isn't allowed by char6.
2977 } else {
2979 AbbrevToUse = String8Abbrev;
2980 }
2981 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2982 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2983 for (uint64_t i = 0; i != NumElts; ++i) {
2984 unsigned char V = Str->getElementAsInteger(i);
2985 Record.push_back(V);
2986 isCStr7 &= (V & 128) == 0;
2987 if (isCStrChar6)
2988 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2989 }
2990
2991 if (isCStrChar6)
2992 AbbrevToUse = CString6Abbrev;
2993 else if (isCStr7)
2994 AbbrevToUse = CString7Abbrev;
2995 } else if (const ConstantDataSequential *CDS =
2998 Type *EltTy = CDS->getElementType();
2999 if (isa<IntegerType>(EltTy) || isa<ByteType>(EltTy)) {
3000 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3001 Record.push_back(CDS->getElementAsInteger(i));
3002 } else {
3003 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3004 Record.push_back(
3005 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
3006 }
3007 } else if (isa<ConstantAggregate>(C)) {
3009 for (const Value *Op : C->operands())
3010 Record.push_back(VE.getValueID(Op));
3011 AbbrevToUse = AggregateAbbrev;
3012 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
3013 switch (CE->getOpcode()) {
3014 default:
3015 if (Instruction::isCast(CE->getOpcode())) {
3017 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
3018 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3019 Record.push_back(VE.getValueID(C->getOperand(0)));
3020 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
3021 } else {
3022 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
3024 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
3025 Record.push_back(VE.getValueID(C->getOperand(0)));
3026 Record.push_back(VE.getValueID(C->getOperand(1)));
3027 uint64_t Flags = getOptimizationFlags(CE);
3028 if (Flags != 0)
3029 Record.push_back(Flags);
3030 }
3031 break;
3032 case Instruction::FNeg: {
3033 assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
3035 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
3036 Record.push_back(VE.getValueID(C->getOperand(0)));
3037 uint64_t Flags = getOptimizationFlags(CE);
3038 if (Flags != 0)
3039 Record.push_back(Flags);
3040 break;
3041 }
3042 case Instruction::GetElementPtr: {
3044 const auto *GO = cast<GEPOperator>(C);
3045 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
3046 Record.push_back(getOptimizationFlags(GO));
3047 if (std::optional<ConstantRange> Range = GO->getInRange()) {
3049 emitConstantRange(Record, *Range, /*EmitBitWidth=*/true);
3050 }
3051 for (const Value *Op : CE->operands()) {
3052 Record.push_back(VE.getTypeID(Op->getType()));
3053 Record.push_back(VE.getValueID(Op));
3054 }
3055 break;
3056 }
3057 case Instruction::ExtractElement:
3059 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3060 Record.push_back(VE.getValueID(C->getOperand(0)));
3061 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
3062 Record.push_back(VE.getValueID(C->getOperand(1)));
3063 break;
3064 case Instruction::InsertElement:
3066 Record.push_back(VE.getValueID(C->getOperand(0)));
3067 Record.push_back(VE.getValueID(C->getOperand(1)));
3068 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
3069 Record.push_back(VE.getValueID(C->getOperand(2)));
3070 break;
3071 case Instruction::ShuffleVector:
3072 // If the return type and argument types are the same, this is a
3073 // standard shufflevector instruction. If the types are different,
3074 // then the shuffle is widening or truncating the input vectors, and
3075 // the argument type must also be encoded.
3076 if (C->getType() == C->getOperand(0)->getType()) {
3078 } else {
3080 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3081 }
3082 Record.push_back(VE.getValueID(C->getOperand(0)));
3083 Record.push_back(VE.getValueID(C->getOperand(1)));
3084 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
3085 break;
3086 }
3087 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
3089 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
3090 Record.push_back(VE.getValueID(BA->getFunction()));
3091 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
3092 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
3094 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
3095 Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
3096 } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
3098 Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
3099 Record.push_back(VE.getValueID(NC->getGlobalValue()));
3100 } else if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C)) {
3102 Record.push_back(VE.getValueID(CPA->getPointer()));
3103 Record.push_back(VE.getValueID(CPA->getKey()));
3104 Record.push_back(VE.getValueID(CPA->getDiscriminator()));
3105 Record.push_back(VE.getValueID(CPA->getAddrDiscriminator()));
3106 Record.push_back(VE.getValueID(CPA->getDeactivationSymbol()));
3107 } else {
3108#ifndef NDEBUG
3109 C->dump();
3110#endif
3111 llvm_unreachable("Unknown constant!");
3112 }
3113 Stream.EmitRecord(Code, Record, AbbrevToUse);
3114 Record.clear();
3115 }
3116
3117 Stream.ExitBlock();
3118}
3119
3120void ModuleBitcodeWriter::writeModuleConstants() {
3121 const ValueEnumerator::ValueList &Vals = VE.getValues();
3122
3123 // Find the first constant to emit, which is the first non-globalvalue value.
3124 // We know globalvalues have been emitted by WriteModuleInfo.
3125 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
3126 if (!isa<GlobalValue>(Vals[i].first)) {
3127 writeConstants(i, Vals.size(), true);
3128 return;
3129 }
3130 }
3131}
3132
3133/// pushValueAndType - The file has to encode both the value and type id for
3134/// many values, because we need to know what type to create for forward
3135/// references. However, most operands are not forward references, so this type
3136/// field is not needed.
3137///
3138/// This function adds V's value ID to Vals. If the value ID is higher than the
3139/// instruction ID, then it is a forward reference, and it also includes the
3140/// type ID. The value ID that is written is encoded relative to the InstID.
3141bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
3142 SmallVectorImpl<unsigned> &Vals) {
3143 unsigned ValID = VE.getValueID(V);
3144 // Make encoding relative to the InstID.
3145 Vals.push_back(InstID - ValID);
3146 if (ValID >= InstID) {
3147 Vals.push_back(VE.getTypeID(V->getType()));
3148 return true;
3149 }
3150 return false;
3151}
3152
3153bool ModuleBitcodeWriter::pushValueOrMetadata(const Value *V, unsigned InstID,
3154 SmallVectorImpl<unsigned> &Vals) {
3155 bool IsMetadata = V->getType()->isMetadataTy();
3156 if (IsMetadata) {
3158 Metadata *MD = cast<MetadataAsValue>(V)->getMetadata();
3159 unsigned ValID = VE.getMetadataID(MD);
3160 Vals.push_back(InstID - ValID);
3161 return false;
3162 }
3163 return pushValueAndType(V, InstID, Vals);
3164}
3165
3166void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
3167 unsigned InstID) {
3169 LLVMContext &C = CS.getContext();
3170
3171 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
3172 const auto &Bundle = CS.getOperandBundleAt(i);
3173 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
3174
3175 for (auto &Input : Bundle.Inputs)
3176 pushValueOrMetadata(Input, InstID, Record);
3177
3179 Record.clear();
3180 }
3181}
3182
3183/// pushValue - Like pushValueAndType, but where the type of the value is
3184/// omitted (perhaps it was already encoded in an earlier operand).
3185void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
3186 SmallVectorImpl<unsigned> &Vals) {
3187 unsigned ValID = VE.getValueID(V);
3188 Vals.push_back(InstID - ValID);
3189}
3190
3191void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
3192 SmallVectorImpl<uint64_t> &Vals) {
3193 unsigned ValID = VE.getValueID(V);
3194 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3195 emitSignedInt64(Vals, diff);
3196}
3197
3198/// WriteInstruction - Emit an instruction to the specified stream.
3199void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
3200 unsigned InstID,
3201 SmallVectorImpl<unsigned> &Vals) {
3202 unsigned Code = 0;
3203 unsigned AbbrevToUse = 0;
3204 VE.setInstructionID(&I);
3205 switch (I.getOpcode()) {
3206 default:
3207 if (Instruction::isCast(I.getOpcode())) {
3209 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3210 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3211 Vals.push_back(VE.getTypeID(I.getType()));
3212 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
3213 uint64_t Flags = getOptimizationFlags(&I);
3214 if (Flags != 0) {
3215 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3216 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3217 Vals.push_back(Flags);
3218 }
3219 } else {
3220 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
3222 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3223 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3224 pushValue(I.getOperand(1), InstID, Vals);
3225 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
3226 uint64_t Flags = getOptimizationFlags(&I);
3227 if (Flags != 0) {
3228 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3229 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3230 Vals.push_back(Flags);
3231 }
3232 }
3233 break;
3234 case Instruction::FNeg: {
3236 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3237 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3238 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
3239 uint64_t Flags = getOptimizationFlags(&I);
3240 if (Flags != 0) {
3241 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3242 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3243 Vals.push_back(Flags);
3244 }
3245 break;
3246 }
3247 case Instruction::GetElementPtr: {
3249 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3250 auto &GEPInst = cast<GetElementPtrInst>(I);
3252 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
3253 for (const Value *Op : I.operands())
3254 pushValueAndType(Op, InstID, Vals);
3255 break;
3256 }
3257 case Instruction::ExtractValue: {
3259 pushValueAndType(I.getOperand(0), InstID, Vals);
3260 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3261 Vals.append(EVI->idx_begin(), EVI->idx_end());
3262 break;
3263 }
3264 case Instruction::InsertValue: {
3266 pushValueAndType(I.getOperand(0), InstID, Vals);
3267 pushValueAndType(I.getOperand(1), InstID, Vals);
3268 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
3269 Vals.append(IVI->idx_begin(), IVI->idx_end());
3270 break;
3271 }
3272 case Instruction::Select: {
3274 pushValueAndType(I.getOperand(1), InstID, Vals);
3275 pushValue(I.getOperand(2), InstID, Vals);
3276 pushValueAndType(I.getOperand(0), InstID, Vals);
3277 uint64_t Flags = getOptimizationFlags(&I);
3278 if (Flags != 0)
3279 Vals.push_back(Flags);
3280 break;
3281 }
3282 case Instruction::ExtractElement:
3284 pushValueAndType(I.getOperand(0), InstID, Vals);
3285 pushValueAndType(I.getOperand(1), InstID, Vals);
3286 break;
3287 case Instruction::InsertElement:
3289 pushValueAndType(I.getOperand(0), InstID, Vals);
3290 pushValue(I.getOperand(1), InstID, Vals);
3291 pushValueAndType(I.getOperand(2), InstID, Vals);
3292 break;
3293 case Instruction::ShuffleVector:
3295 pushValueAndType(I.getOperand(0), InstID, Vals);
3296 pushValue(I.getOperand(1), InstID, Vals);
3297 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
3298 Vals);
3299 break;
3300 case Instruction::ICmp:
3301 case Instruction::FCmp: {
3302 // compare returning Int1Ty or vector of Int1Ty
3304 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3305 if (pushValueAndType(I.getOperand(0), InstID, Vals))
3306 AbbrevToUse = 0;
3307 pushValue(I.getOperand(1), InstID, Vals);
3309 uint64_t Flags = getOptimizationFlags(&I);
3310 if (Flags != 0) {
3311 Vals.push_back(Flags);
3312 if (AbbrevToUse)
3313 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3314 }
3315 break;
3316 }
3317
3318 case Instruction::Ret:
3319 {
3321 unsigned NumOperands = I.getNumOperands();
3322 if (NumOperands == 0)
3323 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3324 else if (NumOperands == 1) {
3325 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3326 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3327 } else {
3328 for (const Value *Op : I.operands())
3329 pushValueAndType(Op, InstID, Vals);
3330 }
3331 }
3332 break;
3333 case Instruction::UncondBr: {
3335 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3336 const UncondBrInst &II = cast<UncondBrInst>(I);
3337 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3338 } break;
3339 case Instruction::CondBr: {
3341 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3342 const CondBrInst &II = cast<CondBrInst>(I);
3343 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3344 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
3345 pushValue(II.getCondition(), InstID, Vals);
3346 } break;
3347 case Instruction::Switch:
3348 {
3350 const SwitchInst &SI = cast<SwitchInst>(I);
3351 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
3352 pushValue(SI.getCondition(), InstID, Vals);
3353 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
3354 for (auto Case : SI.cases()) {
3355 Vals.push_back(VE.getValueID(Case.getCaseValue()));
3356 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
3357 }
3358 }
3359 break;
3360 case Instruction::IndirectBr:
3362 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3363 // Encode the address operand as relative, but not the basic blocks.
3364 pushValue(I.getOperand(0), InstID, Vals);
3365 for (const Value *Op : drop_begin(I.operands()))
3366 Vals.push_back(VE.getValueID(Op));
3367 break;
3368
3369 case Instruction::Invoke: {
3370 const InvokeInst *II = cast<InvokeInst>(&I);
3371 const Value *Callee = II->getCalledOperand();
3372 FunctionType *FTy = II->getFunctionType();
3373
3374 if (II->hasOperandBundles())
3375 writeOperandBundles(*II, InstID);
3376
3378
3379 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
3380 Vals.push_back(II->getCallingConv() | 1 << 13);
3381 Vals.push_back(VE.getValueID(II->getNormalDest()));
3382 Vals.push_back(VE.getValueID(II->getUnwindDest()));
3383 Vals.push_back(VE.getTypeID(FTy));
3384 pushValueAndType(Callee, InstID, Vals);
3385
3386 // Emit value #'s for the fixed parameters.
3387 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3388 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3389
3390 // Emit type/value pairs for varargs params.
3391 if (FTy->isVarArg()) {
3392 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
3393 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3394 }
3395 break;
3396 }
3397 case Instruction::Resume:
3399 pushValueAndType(I.getOperand(0), InstID, Vals);
3400 break;
3401 case Instruction::CleanupRet: {
3403 const auto &CRI = cast<CleanupReturnInst>(I);
3404 pushValue(CRI.getCleanupPad(), InstID, Vals);
3405 if (CRI.hasUnwindDest())
3406 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
3407 break;
3408 }
3409 case Instruction::CatchRet: {
3411 const auto &CRI = cast<CatchReturnInst>(I);
3412 pushValue(CRI.getCatchPad(), InstID, Vals);
3413 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
3414 break;
3415 }
3416 case Instruction::CleanupPad:
3417 case Instruction::CatchPad: {
3418 const auto &FuncletPad = cast<FuncletPadInst>(I);
3421 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3422
3423 unsigned NumArgOperands = FuncletPad.arg_size();
3424 Vals.push_back(NumArgOperands);
3425 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
3426 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
3427 break;
3428 }
3429 case Instruction::CatchSwitch: {
3431 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
3432
3433 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3434
3435 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3436 Vals.push_back(NumHandlers);
3437 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3438 Vals.push_back(VE.getValueID(CatchPadBB));
3439
3440 if (CatchSwitch.hasUnwindDest())
3441 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3442 break;
3443 }
3444 case Instruction::CallBr: {
3445 const CallBrInst *CBI = cast<CallBrInst>(&I);
3446 const Value *Callee = CBI->getCalledOperand();
3447 FunctionType *FTy = CBI->getFunctionType();
3448
3449 if (CBI->hasOperandBundles())
3450 writeOperandBundles(*CBI, InstID);
3451
3453
3455
3458
3459 Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3460 Vals.push_back(CBI->getNumIndirectDests());
3461 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3462 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3463
3464 Vals.push_back(VE.getTypeID(FTy));
3465 pushValueAndType(Callee, InstID, Vals);
3466
3467 // Emit value #'s for the fixed parameters.
3468 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3469 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3470
3471 // Emit type/value pairs for varargs params.
3472 if (FTy->isVarArg()) {
3473 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3474 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3475 }
3476 break;
3477 }
3478 case Instruction::Unreachable:
3480 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3481 break;
3482
3483 case Instruction::PHI: {
3484 const PHINode &PN = cast<PHINode>(I);
3486 // With the newer instruction encoding, forward references could give
3487 // negative valued IDs. This is most common for PHIs, so we use
3488 // signed VBRs.
3490 Vals64.push_back(VE.getTypeID(PN.getType()));
3491 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3492 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3493 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3494 }
3495
3496 uint64_t Flags = getOptimizationFlags(&I);
3497 if (Flags != 0)
3498 Vals64.push_back(Flags);
3499
3500 // Emit a Vals64 vector and exit.
3501 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3502 Vals64.clear();
3503 return;
3504 }
3505
3506 case Instruction::LandingPad: {
3507 const LandingPadInst &LP = cast<LandingPadInst>(I);
3509 Vals.push_back(VE.getTypeID(LP.getType()));
3510 Vals.push_back(LP.isCleanup());
3511 Vals.push_back(LP.getNumClauses());
3512 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3513 if (LP.isCatch(I))
3515 else
3517 pushValueAndType(LP.getClause(I), InstID, Vals);
3518 }
3519 break;
3520 }
3521
3522 case Instruction::Alloca: {
3524 const AllocaInst &AI = cast<AllocaInst>(I);
3525 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3526 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3527 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3528 using APV = AllocaPackedValues;
3529 unsigned Record = 0;
3530 unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3532 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3534 EncodedAlign >> APV::AlignLower::Bits);
3538 Vals.push_back(Record);
3539
3540 unsigned AS = AI.getAddressSpace();
3541 if (AS != M.getDataLayout().getAllocaAddrSpace())
3542 Vals.push_back(AS);
3543 break;
3544 }
3545
3546 case Instruction::Load:
3547 if (cast<LoadInst>(I).isAtomic()) {
3549 pushValueAndType(I.getOperand(0), InstID, Vals);
3550 } else {
3552 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3553 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3554 }
3555 Vals.push_back(VE.getTypeID(I.getType()));
3556 Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3557 Vals.push_back(cast<LoadInst>(I).isVolatile());
3558 if (cast<LoadInst>(I).isAtomic()) {
3559 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3560 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3561 }
3562 break;
3563 case Instruction::Store:
3564 if (cast<StoreInst>(I).isAtomic()) {
3566 } else {
3568 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3569 }
3570 if (pushValueAndType(I.getOperand(1), InstID, Vals)) // ptrty + ptr
3571 AbbrevToUse = 0;
3572 if (pushValueAndType(I.getOperand(0), InstID, Vals)) // valty + val
3573 AbbrevToUse = 0;
3574 Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3575 Vals.push_back(cast<StoreInst>(I).isVolatile());
3576 if (cast<StoreInst>(I).isAtomic()) {
3577 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3578 Vals.push_back(
3579 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3580 }
3581 break;
3582 case Instruction::AtomicCmpXchg:
3584 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3585 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3586 pushValue(I.getOperand(2), InstID, Vals); // newval.
3587 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3588 Vals.push_back(
3589 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3590 Vals.push_back(
3591 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3592 Vals.push_back(
3593 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3594 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3595 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3596 break;
3597 case Instruction::AtomicRMW:
3599 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3600 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3602 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3603 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3604 Vals.push_back(
3605 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3606 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3607 break;
3608 case Instruction::Fence:
3610 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3611 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3612 break;
3613 case Instruction::Call: {
3614 const CallInst &CI = cast<CallInst>(I);
3615 FunctionType *FTy = CI.getFunctionType();
3616
3617 if (CI.hasOperandBundles())
3618 writeOperandBundles(CI, InstID);
3619
3621
3623
3624 unsigned Flags = getOptimizationFlags(&I);
3626 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3627 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3629 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3630 unsigned(Flags != 0) << bitc::CALL_FMF);
3631 if (Flags != 0)
3632 Vals.push_back(Flags);
3633
3634 Vals.push_back(VE.getTypeID(FTy));
3635 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3636
3637 // Emit value #'s for the fixed parameters.
3638 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3639 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3640
3641 // Emit type/value pairs for varargs params.
3642 if (FTy->isVarArg()) {
3643 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3644 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3645 }
3646 break;
3647 }
3648 case Instruction::VAArg:
3650 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3651 pushValue(I.getOperand(0), InstID, Vals); // valist.
3652 Vals.push_back(VE.getTypeID(I.getType())); // restype.
3653 break;
3654 case Instruction::Freeze:
3656 pushValueAndType(I.getOperand(0), InstID, Vals);
3657 break;
3658 }
3659
3660 Stream.EmitRecord(Code, Vals, AbbrevToUse);
3661 Vals.clear();
3662}
3663
3664/// Write a GlobalValue VST to the module. The purpose of this data structure is
3665/// to allow clients to efficiently find the function body.
3666void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3667 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3668 // Get the offset of the VST we are writing, and backpatch it into
3669 // the VST forward declaration record.
3670 uint64_t VSTOffset = Stream.GetCurrentBitNo();
3671 // The BitcodeStartBit was the stream offset of the identification block.
3672 VSTOffset -= bitcodeStartBit();
3673 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3674 // Note that we add 1 here because the offset is relative to one word
3675 // before the start of the identification block, which was historically
3676 // always the start of the regular bitcode header.
3677 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3678
3680
3681 auto Abbv = std::make_shared<BitCodeAbbrev>();
3682 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
3683 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3684 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3685 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3686
3687 for (const Function &F : M) {
3688 uint64_t Record[2];
3689
3690 if (F.isDeclaration())
3691 continue;
3692
3693 Record[0] = VE.getValueID(&F);
3694
3695 // Save the word offset of the function (from the start of the
3696 // actual bitcode written to the stream).
3697 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3698 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3699 // Note that we add 1 here because the offset is relative to one word
3700 // before the start of the identification block, which was historically
3701 // always the start of the regular bitcode header.
3702 Record[1] = BitcodeIndex / 32 + 1;
3703
3704 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3705 }
3706
3707 Stream.ExitBlock();
3708}
3709
3710/// Emit names for arguments, instructions and basic blocks in a function.
3711void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3712 const ValueSymbolTable &VST) {
3713 if (VST.empty())
3714 return;
3715
3717
3718 // FIXME: Set up the abbrev, we know how many values there are!
3719 // FIXME: We know if the type names can use 7-bit ascii.
3720 SmallVector<uint64_t, 64> NameVals;
3721
3722 for (const ValueName &Name : VST) {
3723 // Figure out the encoding to use for the name.
3725
3726 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3727 NameVals.push_back(VE.getValueID(Name.getValue()));
3728
3729 // VST_CODE_ENTRY: [valueid, namechar x N]
3730 // VST_CODE_BBENTRY: [bbid, namechar x N]
3731 unsigned Code;
3732 if (isa<BasicBlock>(Name.getValue())) {
3734 if (Bits == SE_Char6)
3735 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3736 } else {
3738 if (Bits == SE_Char6)
3739 AbbrevToUse = VST_ENTRY_6_ABBREV;
3740 else if (Bits == SE_Fixed7)
3741 AbbrevToUse = VST_ENTRY_7_ABBREV;
3742 }
3743
3744 for (const auto P : Name.getKey())
3745 NameVals.push_back((unsigned char)P);
3746
3747 // Emit the finished record.
3748 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3749 NameVals.clear();
3750 }
3751
3752 Stream.ExitBlock();
3753}
3754
3755void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3756 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3757 unsigned Code;
3758 if (isa<BasicBlock>(Order.V))
3760 else
3762
3763 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3764 Record.push_back(VE.getValueID(Order.V));
3765 Stream.EmitRecord(Code, Record);
3766}
3767
3768void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3770 "Expected to be preserving use-list order");
3771
3772 auto hasMore = [&]() {
3773 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3774 };
3775 if (!hasMore())
3776 // Nothing to do.
3777 return;
3778
3780 while (hasMore()) {
3781 writeUseList(std::move(VE.UseListOrders.back()));
3782 VE.UseListOrders.pop_back();
3783 }
3784 Stream.ExitBlock();
3785}
3786
3787/// Emit a function body to the module stream.
3788void ModuleBitcodeWriter::writeFunction(
3789 const Function &F,
3790 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3791 // Save the bitcode index of the start of this function block for recording
3792 // in the VST.
3793 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3794
3797
3799
3800 // Emit the number of basic blocks, so the reader can create them ahead of
3801 // time.
3802 Vals.push_back(VE.getBasicBlocks().size());
3804 Vals.clear();
3805
3806 // If there are function-local constants, emit them now.
3807 unsigned CstStart, CstEnd;
3808 VE.getFunctionConstantRange(CstStart, CstEnd);
3809 writeConstants(CstStart, CstEnd, false);
3810
3811 // If there is function-local metadata, emit it now.
3812 writeFunctionMetadata(F);
3813
3814 // Keep a running idea of what the instruction ID is.
3815 unsigned InstID = CstEnd;
3816
3817 bool NeedsMetadataAttachment = F.hasMetadata();
3818
3819 DILocation *LastDL = nullptr;
3820 SmallSetVector<Function *, 4> BlockAddressUsers;
3821
3822 // Finally, emit all the instructions, in order.
3823 for (const BasicBlock &BB : F) {
3824 for (const Instruction &I : BB) {
3825 writeInstruction(I, InstID, Vals);
3826
3827 if (!I.getType()->isVoidTy())
3828 ++InstID;
3829
3830 // If the instruction has metadata, write a metadata attachment later.
3831 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3832
3833 // If the instruction has a debug location, emit it.
3834 if (DILocation *DL = I.getDebugLoc()) {
3835 if (DL == LastDL) {
3836 // Just repeat the same debug loc as last time.
3838 } else {
3839 Vals.push_back(DL->getLine());
3840 Vals.push_back(DL->getColumn());
3841 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3842 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3843 Vals.push_back(DL->isImplicitCode());
3844 Vals.push_back(DL->getAtomGroup());
3845 Vals.push_back(DL->getAtomRank());
3847 FUNCTION_DEBUG_LOC_ABBREV);
3848 Vals.clear();
3849 LastDL = DL;
3850 }
3851 }
3852
3853 // If the instruction has DbgRecords attached to it, emit them. Note that
3854 // they come after the instruction so that it's easy to attach them again
3855 // when reading the bitcode, even though conceptually the debug locations
3856 // start "before" the instruction.
3857 if (I.hasDbgRecords()) {
3858 /// Try to push the value only (unwrapped), otherwise push the
3859 /// metadata wrapped value. Returns true if the value was pushed
3860 /// without the ValueAsMetadata wrapper.
3861 auto PushValueOrMetadata = [&Vals, InstID,
3862 this](Metadata *RawLocation) {
3863 assert(RawLocation &&
3864 "RawLocation unexpectedly null in DbgVariableRecord");
3865 if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) {
3866 SmallVector<unsigned, 2> ValAndType;
3867 // If the value is a fwd-ref the type is also pushed. We don't
3868 // want the type, so fwd-refs are kept wrapped (pushValueAndType
3869 // returns false if the value is pushed without type).
3870 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
3871 Vals.push_back(ValAndType[0]);
3872 return true;
3873 }
3874 }
3875 // The metadata is a DIArgList, or ValueAsMetadata wrapping a
3876 // fwd-ref. Push the metadata ID.
3877 Vals.push_back(VE.getMetadataID(RawLocation));
3878 return false;
3879 };
3880
3881 // Write out non-instruction debug information attached to this
3882 // instruction. Write it after the instruction so that it's easy to
3883 // re-attach to the instruction reading the records in.
3884 for (DbgRecord &DR : I.DebugMarker->getDbgRecordRange()) {
3885 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
3886 Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc()));
3887 Vals.push_back(VE.getMetadataID(DLR->getLabel()));
3889 Vals.clear();
3890 continue;
3891 }
3892
3893 // First 3 fields are common to all kinds:
3894 // DILocation, DILocalVariable, DIExpression
3895 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
3896 // ..., LocationMetadata
3897 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
3898 // ..., Value
3899 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
3900 // ..., LocationMetadata
3901 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
3902 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
3903 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
3904 Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc()));
3905 Vals.push_back(VE.getMetadataID(DVR.getVariable()));
3906 Vals.push_back(VE.getMetadataID(DVR.getExpression()));
3907 if (DVR.isDbgValue()) {
3908 if (PushValueOrMetadata(DVR.getRawLocation()))
3910 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
3911 else
3913 } else if (DVR.isDbgDeclare()) {
3914 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3916 } else if (DVR.isDbgDeclareValue()) {
3917 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3919 } else {
3920 assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind");
3921 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3922 Vals.push_back(VE.getMetadataID(DVR.getAssignID()));
3924 Vals.push_back(VE.getMetadataID(DVR.getRawAddress()));
3926 }
3927 Vals.clear();
3928 }
3929 }
3930 }
3931
3932 if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
3933 SmallVector<Value *> Worklist{BA};
3934 SmallPtrSet<Value *, 8> Visited{BA};
3935 while (!Worklist.empty()) {
3936 Value *V = Worklist.pop_back_val();
3937 for (User *U : V->users()) {
3938 if (auto *I = dyn_cast<Instruction>(U)) {
3939 Function *P = I->getFunction();
3940 if (P != &F)
3941 BlockAddressUsers.insert(P);
3942 } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
3943 Visited.insert(U).second)
3944 Worklist.push_back(U);
3945 }
3946 }
3947 }
3948 }
3949
3950 if (!BlockAddressUsers.empty()) {
3951 Vals.resize(BlockAddressUsers.size());
3952 for (auto I : llvm::enumerate(BlockAddressUsers))
3953 Vals[I.index()] = VE.getValueID(I.value());
3955 Vals.clear();
3956 }
3957
3958 // Emit names for all the instructions etc.
3959 if (auto *Symtab = F.getValueSymbolTable())
3960 writeFunctionLevelValueSymbolTable(*Symtab);
3961
3962 if (NeedsMetadataAttachment)
3963 writeFunctionMetadataAttachment(F);
3965 writeUseListBlock(&F);
3966 VE.purgeFunction();
3967 Stream.ExitBlock();
3968}
3969
3970// Emit blockinfo, which defines the standard abbreviations etc.
3971void ModuleBitcodeWriter::writeBlockInfo() {
3972 // We only want to emit block info records for blocks that have multiple
3973 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3974 // Other blocks can define their abbrevs inline.
3975 Stream.EnterBlockInfoBlock();
3976
3977 // Encode type indices using fixed size based on number of types.
3978 BitCodeAbbrevOp TypeAbbrevOp(BitCodeAbbrevOp::Fixed,
3980 // Encode value indices as 6-bit VBR.
3981 BitCodeAbbrevOp ValAbbrevOp(BitCodeAbbrevOp::VBR, 6);
3982
3983 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3984 auto Abbv = std::make_shared<BitCodeAbbrev>();
3985 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3986 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3987 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3988 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3990 VST_ENTRY_8_ABBREV)
3991 llvm_unreachable("Unexpected abbrev ordering!");
3992 }
3993
3994 { // 7-bit fixed width VST_CODE_ENTRY strings.
3995 auto Abbv = std::make_shared<BitCodeAbbrev>();
3996 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3997 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3998 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3999 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
4001 VST_ENTRY_7_ABBREV)
4002 llvm_unreachable("Unexpected abbrev ordering!");
4003 }
4004 { // 6-bit char6 VST_CODE_ENTRY strings.
4005 auto Abbv = std::make_shared<BitCodeAbbrev>();
4006 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
4007 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4008 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4009 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4011 VST_ENTRY_6_ABBREV)
4012 llvm_unreachable("Unexpected abbrev ordering!");
4013 }
4014 { // 6-bit char6 VST_CODE_BBENTRY strings.
4015 auto Abbv = std::make_shared<BitCodeAbbrev>();
4016 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
4017 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4018 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4019 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4021 VST_BBENTRY_6_ABBREV)
4022 llvm_unreachable("Unexpected abbrev ordering!");
4023 }
4024
4025 { // SETTYPE abbrev for CONSTANTS_BLOCK.
4026 auto Abbv = std::make_shared<BitCodeAbbrev>();
4027 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
4028 Abbv->Add(TypeAbbrevOp);
4030 CONSTANTS_SETTYPE_ABBREV)
4031 llvm_unreachable("Unexpected abbrev ordering!");
4032 }
4033
4034 { // INTEGER abbrev for CONSTANTS_BLOCK.
4035 auto Abbv = std::make_shared<BitCodeAbbrev>();
4036 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
4037 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4039 CONSTANTS_INTEGER_ABBREV)
4040 llvm_unreachable("Unexpected abbrev ordering!");
4041 }
4042
4043 { // BYTE abbrev for CONSTANTS_BLOCK.
4044 auto Abbv = std::make_shared<BitCodeAbbrev>();
4045 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_BYTE));
4046 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4048 CONSTANTS_BYTE_ABBREV)
4049 llvm_unreachable("Unexpected abbrev ordering!");
4050 }
4051
4052 { // CE_CAST abbrev for CONSTANTS_BLOCK.
4053 auto Abbv = std::make_shared<BitCodeAbbrev>();
4054 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
4055 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
4056 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
4058 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
4059
4061 CONSTANTS_CE_CAST_Abbrev)
4062 llvm_unreachable("Unexpected abbrev ordering!");
4063 }
4064 { // NULL abbrev for CONSTANTS_BLOCK.
4065 auto Abbv = std::make_shared<BitCodeAbbrev>();
4066 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
4068 CONSTANTS_NULL_Abbrev)
4069 llvm_unreachable("Unexpected abbrev ordering!");
4070 }
4071
4072 // FIXME: This should only use space for first class types!
4073
4074 { // INST_LOAD abbrev for FUNCTION_BLOCK.
4075 auto Abbv = std::make_shared<BitCodeAbbrev>();
4076 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
4077 Abbv->Add(ValAbbrevOp); // Ptr
4078 Abbv->Add(TypeAbbrevOp); // dest ty
4079 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
4080 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
4081 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4082 FUNCTION_INST_LOAD_ABBREV)
4083 llvm_unreachable("Unexpected abbrev ordering!");
4084 }
4085 {
4086 auto Abbv = std::make_shared<BitCodeAbbrev>();
4087 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_STORE));
4088 Abbv->Add(ValAbbrevOp); // op1
4089 Abbv->Add(ValAbbrevOp); // op0
4090 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // align
4091 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
4092 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4093 FUNCTION_INST_STORE_ABBREV)
4094 llvm_unreachable("Unexpected abbrev ordering!");
4095 }
4096 { // INST_UNOP abbrev for FUNCTION_BLOCK.
4097 auto Abbv = std::make_shared<BitCodeAbbrev>();
4098 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
4099 Abbv->Add(ValAbbrevOp); // LHS
4100 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4101 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4102 FUNCTION_INST_UNOP_ABBREV)
4103 llvm_unreachable("Unexpected abbrev ordering!");
4104 }
4105 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
4106 auto Abbv = std::make_shared<BitCodeAbbrev>();
4107 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
4108 Abbv->Add(ValAbbrevOp); // LHS
4109 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4110 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4111 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4112 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4113 llvm_unreachable("Unexpected abbrev ordering!");
4114 }
4115 { // INST_BINOP abbrev for FUNCTION_BLOCK.
4116 auto Abbv = std::make_shared<BitCodeAbbrev>();
4117 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
4118 Abbv->Add(ValAbbrevOp); // LHS
4119 Abbv->Add(ValAbbrevOp); // RHS
4120 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4121 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4122 FUNCTION_INST_BINOP_ABBREV)
4123 llvm_unreachable("Unexpected abbrev ordering!");
4124 }
4125 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
4126 auto Abbv = std::make_shared<BitCodeAbbrev>();
4127 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
4128 Abbv->Add(ValAbbrevOp); // LHS
4129 Abbv->Add(ValAbbrevOp); // RHS
4130 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4131 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4132 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4133 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4134 llvm_unreachable("Unexpected abbrev ordering!");
4135 }
4136 { // INST_CAST abbrev for FUNCTION_BLOCK.
4137 auto Abbv = std::make_shared<BitCodeAbbrev>();
4138 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
4139 Abbv->Add(ValAbbrevOp); // OpVal
4140 Abbv->Add(TypeAbbrevOp); // dest ty
4141 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4142 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4143 FUNCTION_INST_CAST_ABBREV)
4144 llvm_unreachable("Unexpected abbrev ordering!");
4145 }
4146 { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
4147 auto Abbv = std::make_shared<BitCodeAbbrev>();
4148 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
4149 Abbv->Add(ValAbbrevOp); // OpVal
4150 Abbv->Add(TypeAbbrevOp); // dest ty
4151 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4152 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4153 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4154 FUNCTION_INST_CAST_FLAGS_ABBREV)
4155 llvm_unreachable("Unexpected abbrev ordering!");
4156 }
4157
4158 { // INST_RET abbrev for FUNCTION_BLOCK.
4159 auto Abbv = std::make_shared<BitCodeAbbrev>();
4160 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
4161 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4162 FUNCTION_INST_RET_VOID_ABBREV)
4163 llvm_unreachable("Unexpected abbrev ordering!");
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 Abbv->Add(ValAbbrevOp);
4169 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4170 FUNCTION_INST_RET_VAL_ABBREV)
4171 llvm_unreachable("Unexpected abbrev ordering!");
4172 }
4173 {
4174 auto Abbv = std::make_shared<BitCodeAbbrev>();
4175 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BR));
4176 // TODO: Use different abbrev for absolute value reference (succ0)?
4177 Abbv->Add(ValAbbrevOp); // succ0
4178 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4179 FUNCTION_INST_BR_UNCOND_ABBREV)
4180 llvm_unreachable("Unexpected abbrev ordering!");
4181 }
4182 {
4183 auto Abbv = std::make_shared<BitCodeAbbrev>();
4184 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BR));
4185 // TODO: Use different abbrev for absolute value references (succ0, succ1)?
4186 Abbv->Add(ValAbbrevOp); // succ0
4187 Abbv->Add(ValAbbrevOp); // succ1
4188 Abbv->Add(ValAbbrevOp); // cond
4189 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4190 FUNCTION_INST_BR_COND_ABBREV)
4191 llvm_unreachable("Unexpected abbrev ordering!");
4192 }
4193 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
4194 auto Abbv = std::make_shared<BitCodeAbbrev>();
4195 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
4196 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4197 FUNCTION_INST_UNREACHABLE_ABBREV)
4198 llvm_unreachable("Unexpected abbrev ordering!");
4199 }
4200 {
4201 auto Abbv = std::make_shared<BitCodeAbbrev>();
4202 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
4203 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // flags
4204 Abbv->Add(TypeAbbrevOp); // dest ty
4205 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4206 Abbv->Add(ValAbbrevOp);
4207 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4208 FUNCTION_INST_GEP_ABBREV)
4209 llvm_unreachable("Unexpected abbrev ordering!");
4210 }
4211 {
4212 auto Abbv = std::make_shared<BitCodeAbbrev>();
4213 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CMP2));
4214 Abbv->Add(ValAbbrevOp); // op0
4215 Abbv->Add(ValAbbrevOp); // op1
4216 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 6)); // pred
4217 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4218 FUNCTION_INST_CMP_ABBREV)
4219 llvm_unreachable("Unexpected abbrev ordering!");
4220 }
4221 {
4222 auto Abbv = std::make_shared<BitCodeAbbrev>();
4223 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CMP2));
4224 Abbv->Add(ValAbbrevOp); // op0
4225 Abbv->Add(ValAbbrevOp); // op1
4226 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 6)); // pred
4227 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4228 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4229 FUNCTION_INST_CMP_FLAGS_ABBREV)
4230 llvm_unreachable("Unexpected abbrev ordering!");
4231 }
4232 {
4233 auto Abbv = std::make_shared<BitCodeAbbrev>();
4234 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE));
4235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc
4236 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var
4237 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr
4238 Abbv->Add(ValAbbrevOp); // val
4239 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4240 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4241 llvm_unreachable("Unexpected abbrev ordering! 1");
4242 }
4243 {
4244 auto Abbv = std::make_shared<BitCodeAbbrev>();
4245 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_LOC));
4246 // NOTE: No IsDistinct field for FUNC_CODE_DEBUG_LOC.
4247 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4248 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4249 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4250 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4251 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
4252 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Atom group.
4253 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Atom rank.
4254 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4255 FUNCTION_DEBUG_LOC_ABBREV)
4256 llvm_unreachable("Unexpected abbrev ordering!");
4257 }
4258 Stream.ExitBlock();
4259}
4260
4261/// Write the module path strings, currently only used when generating
4262/// a combined index file.
4263void IndexBitcodeWriter::writeModStrings() {
4265
4266 // TODO: See which abbrev sizes we actually need to emit
4267
4268 // 8-bit fixed-width MST_ENTRY strings.
4269 auto Abbv = std::make_shared<BitCodeAbbrev>();
4270 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4271 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4272 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4273 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
4274 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
4275
4276 // 7-bit fixed width MST_ENTRY strings.
4277 Abbv = std::make_shared<BitCodeAbbrev>();
4278 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4279 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4280 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4281 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
4282 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
4283
4284 // 6-bit char6 MST_ENTRY strings.
4285 Abbv = std::make_shared<BitCodeAbbrev>();
4286 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4287 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4288 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4289 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4290 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
4291
4292 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
4293 Abbv = std::make_shared<BitCodeAbbrev>();
4294 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
4295 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4296 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4297 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4298 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4299 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4300 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
4301
4303 forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
4304 StringRef Key = MPSE.getKey();
4305 const auto &Hash = MPSE.getValue();
4307 unsigned AbbrevToUse = Abbrev8Bit;
4308 if (Bits == SE_Char6)
4309 AbbrevToUse = Abbrev6Bit;
4310 else if (Bits == SE_Fixed7)
4311 AbbrevToUse = Abbrev7Bit;
4312
4313 auto ModuleId = ModuleIdMap.size();
4314 ModuleIdMap[Key] = ModuleId;
4315 Vals.push_back(ModuleId);
4316 // Use bytes_begin/end() for unsigned char iteration.
4317 Vals.append(Key.bytes_begin(), Key.bytes_end());
4318
4319 // Emit the finished record.
4320 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
4321
4322 // Emit an optional hash for the module now
4323 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
4324 Vals.assign(Hash.begin(), Hash.end());
4325 // Emit the hash record.
4326 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
4327 }
4328
4329 Vals.clear();
4330 });
4331 Stream.ExitBlock();
4332}
4333
4334/// Write the function type metadata related records that need to appear before
4335/// a function summary entry (whether per-module or combined).
4336template <typename Fn>
4338 FunctionSummary *FS,
4339 Fn GetValueID) {
4340 if (!FS->type_tests().empty())
4341 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
4342
4344
4345 auto WriteVFuncIdVec = [&](uint64_t Ty,
4347 if (VFs.empty())
4348 return;
4349 Record.clear();
4350 for (auto &VF : VFs) {
4351 Record.push_back(VF.GUID);
4352 Record.push_back(VF.Offset);
4353 }
4354 Stream.EmitRecord(Ty, Record);
4355 };
4356
4357 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
4358 FS->type_test_assume_vcalls());
4359 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
4360 FS->type_checked_load_vcalls());
4361
4362 auto WriteConstVCallVec = [&](uint64_t Ty,
4364 for (auto &VC : VCs) {
4365 Record.clear();
4366 Record.push_back(VC.VFunc.GUID);
4367 Record.push_back(VC.VFunc.Offset);
4368 llvm::append_range(Record, VC.Args);
4369 Stream.EmitRecord(Ty, Record);
4370 }
4371 };
4372
4373 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
4374 FS->type_test_assume_const_vcalls());
4375 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
4376 FS->type_checked_load_const_vcalls());
4377
4378 auto WriteRange = [&](ConstantRange Range) {
4380 assert(Range.getLower().getNumWords() == 1);
4381 assert(Range.getUpper().getNumWords() == 1);
4382 emitSignedInt64(Record, *Range.getLower().getRawData());
4383 emitSignedInt64(Record, *Range.getUpper().getRawData());
4384 };
4385
4386 if (!FS->paramAccesses().empty()) {
4387 Record.clear();
4388 for (auto &Arg : FS->paramAccesses()) {
4389 size_t UndoSize = Record.size();
4390 Record.push_back(Arg.ParamNo);
4391 WriteRange(Arg.Use);
4392 Record.push_back(Arg.Calls.size());
4393 for (auto &Call : Arg.Calls) {
4394 Record.push_back(Call.ParamNo);
4395 std::optional<unsigned> ValueID = GetValueID(Call.Callee);
4396 if (!ValueID) {
4397 // If ValueID is unknown we can't drop just this call, we must drop
4398 // entire parameter.
4399 Record.resize(UndoSize);
4400 break;
4401 }
4402 Record.push_back(*ValueID);
4403 WriteRange(Call.Offsets);
4404 }
4405 }
4406 if (!Record.empty())
4408 }
4409}
4410
4411/// Collect type IDs from type tests used by function.
4412static void
4414 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4415 if (!FS->type_tests().empty())
4416 for (auto &TT : FS->type_tests())
4417 ReferencedTypeIds.insert(TT);
4418
4419 auto GetReferencedTypesFromVFuncIdVec =
4421 for (auto &VF : VFs)
4422 ReferencedTypeIds.insert(VF.GUID);
4423 };
4424
4425 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4426 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4427
4428 auto GetReferencedTypesFromConstVCallVec =
4430 for (auto &VC : VCs)
4431 ReferencedTypeIds.insert(VC.VFunc.GUID);
4432 };
4433
4434 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4435 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4436}
4437
4439 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
4441 NameVals.push_back(args.size());
4442 llvm::append_range(NameVals, args);
4443
4444 NameVals.push_back(ByArg.TheKind);
4445 NameVals.push_back(ByArg.Info);
4446 NameVals.push_back(ByArg.Byte);
4447 NameVals.push_back(ByArg.Bit);
4448}
4449
4451 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4452 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
4453 NameVals.push_back(Id);
4454
4455 NameVals.push_back(Wpd.TheKind);
4456 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
4457 NameVals.push_back(Wpd.SingleImplName.size());
4458
4459 NameVals.push_back(Wpd.ResByArg.size());
4460 for (auto &A : Wpd.ResByArg)
4461 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
4462}
4463
4465 StringTableBuilder &StrtabBuilder,
4466 StringRef Id,
4467 const TypeIdSummary &Summary) {
4468 NameVals.push_back(StrtabBuilder.add(Id));
4469 NameVals.push_back(Id.size());
4470
4471 NameVals.push_back(Summary.TTRes.TheKind);
4472 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
4473 NameVals.push_back(Summary.TTRes.AlignLog2);
4474 NameVals.push_back(Summary.TTRes.SizeM1);
4475 NameVals.push_back(Summary.TTRes.BitMask);
4476 NameVals.push_back(Summary.TTRes.InlineBits);
4477
4478 for (auto &W : Summary.WPDRes)
4479 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
4480 W.second);
4481}
4482
4484 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4485 StringRef Id, const TypeIdCompatibleVtableInfo &Summary,
4487 NameVals.push_back(StrtabBuilder.add(Id));
4488 NameVals.push_back(Id.size());
4489
4490 for (auto &P : Summary) {
4491 NameVals.push_back(P.AddressPointOffset);
4492 NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
4493 }
4494}
4495
4496// Adds the allocation contexts to the CallStacks map. We simply use the
4497// size at the time the context was added as the CallStackId. This works because
4498// when we look up the call stacks later on we process the function summaries
4499// and their allocation records in the same exact order.
4501 FunctionSummary *FS, std::function<LinearFrameId(unsigned)> GetStackIndex,
4503 // The interfaces in ProfileData/MemProf.h use a type alias for a stack frame
4504 // id offset into the index of the full stack frames. The ModuleSummaryIndex
4505 // currently uses unsigned. Make sure these stay in sync.
4506 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4507 for (auto &AI : FS->allocs()) {
4508 for (auto &MIB : AI.MIBs) {
4509 SmallVector<unsigned> StackIdIndices;
4510 StackIdIndices.reserve(MIB.StackIdIndices.size());
4511 for (auto Id : MIB.StackIdIndices)
4512 StackIdIndices.push_back(GetStackIndex(Id));
4513 // The CallStackId is the size at the time this context was inserted.
4514 CallStacks.insert({CallStacks.size(), StackIdIndices});
4515 }
4516 }
4517}
4518
4519// Build the radix tree from the accumulated CallStacks, write out the resulting
4520// linearized radix tree array, and return the map of call stack positions into
4521// this array for use when writing the allocation records. The returned map is
4522// indexed by a CallStackId which in this case is implicitly determined by the
4523// order of function summaries and their allocation infos being written.
4526 BitstreamWriter &Stream, unsigned RadixAbbrev) {
4527 assert(!CallStacks.empty());
4528 DenseMap<unsigned, FrameStat> FrameHistogram =
4531 // We don't need a MemProfFrameIndexes map as we have already converted the
4532 // full stack id hash to a linear offset into the StackIds array.
4533 Builder.build(std::move(CallStacks), /*MemProfFrameIndexes=*/nullptr,
4534 FrameHistogram);
4535 Stream.EmitRecord(bitc::FS_CONTEXT_RADIX_TREE_ARRAY, Builder.getRadixArray(),
4536 RadixAbbrev);
4537 return Builder.takeCallStackPos();
4538}
4539
4541 BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
4542 unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule,
4543 std::function<unsigned(const ValueInfo &VI)> GetValueID,
4544 std::function<unsigned(unsigned)> GetStackIndex,
4545 bool WriteContextSizeInfoIndex,
4547 CallStackId &CallStackCount) {
4549
4550 for (auto &CI : FS->callsites()) {
4551 Record.clear();
4552 // Per module callsite clones should always have a single entry of
4553 // value 0.
4554 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4555 Record.push_back(GetValueID(CI.Callee));
4556 if (!PerModule) {
4557 Record.push_back(CI.StackIdIndices.size());
4558 Record.push_back(CI.Clones.size());
4559 }
4560 for (auto Id : CI.StackIdIndices)
4561 Record.push_back(GetStackIndex(Id));
4562 if (!PerModule)
4563 llvm::append_range(Record, CI.Clones);
4566 Record, CallsiteAbbrev);
4567 }
4568
4569 for (auto &AI : FS->allocs()) {
4570 Record.clear();
4571 // Per module alloc versions should always have a single entry of
4572 // value 0.
4573 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4574 Record.push_back(AI.MIBs.size());
4575 if (!PerModule)
4576 Record.push_back(AI.Versions.size());
4577 for (auto &MIB : AI.MIBs) {
4578 Record.push_back((uint8_t)MIB.AllocType);
4579 // The per-module summary always needs to include the alloc context, as we
4580 // use it during the thin link. For the combined index it is optional (see
4581 // comments where CombinedIndexMemProfContext is defined).
4582 if (PerModule || CombinedIndexMemProfContext) {
4583 // Record the index into the radix tree array for this context.
4584 assert(CallStackCount <= CallStackPos.size());
4585 Record.push_back(CallStackPos[CallStackCount++]);
4586 }
4587 }
4588 if (!PerModule)
4589 llvm::append_range(Record, AI.Versions);
4590 assert(AI.ContextSizeInfos.empty() ||
4591 AI.ContextSizeInfos.size() == AI.MIBs.size());
4592 // Optionally emit the context size information if it exists.
4593 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4594 // The abbreviation id for the context ids record should have been created
4595 // if we are emitting the per-module index, which is where we write this
4596 // info.
4597 assert(ContextIdAbbvId);
4598 SmallVector<uint32_t> ContextIds;
4599 // At least one context id per ContextSizeInfos entry (MIB), broken into 2
4600 // halves.
4601 ContextIds.reserve(AI.ContextSizeInfos.size() * 2);
4602 for (auto &Infos : AI.ContextSizeInfos) {
4603 Record.push_back(Infos.size());
4604 for (auto [FullStackId, TotalSize] : Infos) {
4605 // The context ids are emitted separately as a fixed width array,
4606 // which is more efficient than a VBR given that these hashes are
4607 // typically close to 64-bits. The max fixed width entry is 32 bits so
4608 // it is split into 2.
4609 ContextIds.push_back(static_cast<uint32_t>(FullStackId >> 32));
4610 ContextIds.push_back(static_cast<uint32_t>(FullStackId));
4611 Record.push_back(TotalSize);
4612 }
4613 }
4614 // The context ids are expected by the reader to immediately precede the
4615 // associated alloc info record.
4616 Stream.EmitRecord(bitc::FS_ALLOC_CONTEXT_IDS, ContextIds,
4617 ContextIdAbbvId);
4618 }
4619 Stream.EmitRecord(PerModule
4624 Record, AllocAbbrev);
4625 }
4626}
4627
4628// Helper to emit a single function summary record.
4629void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4630 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4631 unsigned ValueID, unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
4632 unsigned AllocAbbrev, unsigned ContextIdAbbvId, const Function &F,
4633 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4634 CallStackId &CallStackCount) {
4635 NameVals.push_back(ValueID);
4636
4637 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4638
4640 Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
4641 return {VE.getValueID(VI.getValue())};
4642 });
4643
4644 auto SpecialRefCnts = FS->specialRefCounts();
4645 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4646 NameVals.push_back(FS->instCount());
4647 NameVals.push_back(getEncodedFFlags(FS->fflags()));
4648 NameVals.push_back(FS->refs().size());
4649 NameVals.push_back(SpecialRefCnts.first); // rorefcnt
4650 NameVals.push_back(SpecialRefCnts.second); // worefcnt
4651
4652 for (auto &RI : FS->refs())
4653 NameVals.push_back(getValueId(RI));
4654
4655 for (auto &ECI : FS->calls()) {
4656 NameVals.push_back(getValueId(ECI.first));
4657 NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));
4658 }
4659
4660 // Emit the finished record.
4661 Stream.EmitRecord(bitc::FS_PERMODULE_PROFILE, NameVals, FSCallsProfileAbbrev);
4662 NameVals.clear();
4663
4665 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4666 /*PerModule*/ true,
4667 /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
4668 /*GetStackIndex*/ [&](unsigned I) { return I; },
4669 /*WriteContextSizeInfoIndex*/ true, CallStackPos, CallStackCount);
4670}
4671
4672// Collect the global value references in the given variable's initializer,
4673// and emit them in a summary record.
4674void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4675 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4676 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
4677 auto VI = Index->getValueInfo(V.getGUID());
4678 if (!VI || VI.getSummaryList().empty()) {
4679 // Only declarations should not have a summary (a declaration might however
4680 // have a summary if the def was in module level asm).
4681 assert(V.isDeclaration());
4682 return;
4683 }
4684 auto *Summary = VI.getSummaryList()[0].get();
4685 NameVals.push_back(VE.getValueID(&V));
4686 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
4687 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4688 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4689
4690 auto VTableFuncs = VS->vTableFuncs();
4691 if (!VTableFuncs.empty())
4692 NameVals.push_back(VS->refs().size());
4693
4694 unsigned SizeBeforeRefs = NameVals.size();
4695 for (auto &RI : VS->refs())
4696 NameVals.push_back(VE.getValueID(RI.getValue()));
4697 // Sort the refs for determinism output, the vector returned by FS->refs() has
4698 // been initialized from a DenseSet.
4699 llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
4700
4701 if (VTableFuncs.empty())
4703 FSModRefsAbbrev);
4704 else {
4705 // VTableFuncs pairs should already be sorted by offset.
4706 for (auto &P : VTableFuncs) {
4707 NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
4708 NameVals.push_back(P.VTableOffset);
4709 }
4710
4712 FSModVTableRefsAbbrev);
4713 }
4714 NameVals.clear();
4715}
4716
4717/// Emit the per-module summary section alongside the rest of
4718/// the module's bitcode.
4719void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4720 // By default we compile with ThinLTO if the module has a summary, but the
4721 // client can request full LTO with a module flag.
4722 bool IsThinLTO = true;
4723 if (auto *MD =
4724 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
4725 IsThinLTO = MD->getZExtValue();
4728 4);
4729
4730 Stream.EmitRecord(
4732 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
4733
4734 // Write the index flags.
4735 uint64_t Flags = 0;
4736 // Bits 1-3 are set only in the combined index, skip them.
4737 if (Index->enableSplitLTOUnit())
4738 Flags |= 0x8;
4739 if (Index->hasUnifiedLTO())
4740 Flags |= 0x200;
4741
4742 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
4743
4744 if (Index->begin() == Index->end()) {
4745 Stream.ExitBlock();
4746 return;
4747 }
4748
4749 auto Abbv = std::make_shared<BitCodeAbbrev>();
4750 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID));
4751 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4752 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
4753 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4754 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4755 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4756
4757 for (const auto &GVI : valueIds()) {
4759 ArrayRef<uint32_t>{GVI.second,
4760 static_cast<uint32_t>(GVI.first >> 32),
4761 static_cast<uint32_t>(GVI.first)},
4762 ValueGuidAbbrev);
4763 }
4764
4765 if (!Index->stackIds().empty()) {
4766 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4767 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4768 // numids x stackid
4769 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4770 // The stack ids are hashes that are close to 64 bits in size, so emitting
4771 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
4772 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4773 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4774 SmallVector<uint32_t> Vals;
4775 Vals.reserve(Index->stackIds().size() * 2);
4776 for (auto Id : Index->stackIds()) {
4777 Vals.push_back(static_cast<uint32_t>(Id >> 32));
4778 Vals.push_back(static_cast<uint32_t>(Id));
4779 }
4780 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
4781 }
4782
4783 unsigned ContextIdAbbvId = 0;
4785 // n x context id
4786 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4787 ContextIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_ALLOC_CONTEXT_IDS));
4788 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4789 // The context ids are hashes that are close to 64 bits in size, so emitting
4790 // as a pair of 32-bit fixed-width values is more efficient than a VBR if we
4791 // are emitting them for all MIBs. Otherwise we use VBR to better compress 0
4792 // values that are expected to more frequently occur in an alloc's memprof
4793 // summary.
4795 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4796 else
4797 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4798 ContextIdAbbvId = Stream.EmitAbbrev(std::move(ContextIdAbbv));
4799 }
4800
4801 // Abbrev for FS_PERMODULE_PROFILE.
4802 Abbv = std::make_shared<BitCodeAbbrev>();
4803 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
4804 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4805 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags
4806 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4807 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4808 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4809 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4810 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4811 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4812 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4813 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4814 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4815
4816 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4817 Abbv = std::make_shared<BitCodeAbbrev>();
4818 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
4819 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4820 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4821 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4822 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4823 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4824
4825 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4826 Abbv = std::make_shared<BitCodeAbbrev>();
4827 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
4828 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4829 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4830 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4831 // numrefs x valueid, n x (valueid , offset)
4832 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4833 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4834 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4835
4836 // Abbrev for FS_ALIAS.
4837 Abbv = std::make_shared<BitCodeAbbrev>();
4838 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4839 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4840 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4841 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4842 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4843
4844 // Abbrev for FS_TYPE_ID_METADATA
4845 Abbv = std::make_shared<BitCodeAbbrev>();
4846 Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
4847 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4848 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4849 // n x (valueid , offset)
4850 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4851 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4852 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4853
4854 Abbv = std::make_shared<BitCodeAbbrev>();
4855 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_CALLSITE_INFO));
4856 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4857 // n x stackidindex
4858 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4859 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4860 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4861
4862 Abbv = std::make_shared<BitCodeAbbrev>();
4863 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_ALLOC_INFO));
4864 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
4865 // n x (alloc type, context radix tree index)
4866 // optional: nummib x (numcontext x total size)
4867 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4868 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4869 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4870
4871 Abbv = std::make_shared<BitCodeAbbrev>();
4872 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CONTEXT_RADIX_TREE_ARRAY));
4873 // n x entry
4874 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4875 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4876 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4877
4878 // First walk through all the functions and collect the allocation contexts in
4879 // their associated summaries, for use in constructing a radix tree of
4880 // contexts. Note that we need to do this in the same order as the functions
4881 // are processed further below since the call stack positions in the resulting
4882 // radix tree array are identified based on this order.
4883 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
4884 for (const Function &F : M) {
4885 // Summary emission does not support anonymous functions, they have to be
4886 // renamed using the anonymous function renaming pass.
4887 if (!F.hasName())
4888 report_fatal_error("Unexpected anonymous function when writing summary");
4889
4890 ValueInfo VI = Index->getValueInfo(F.getGUID());
4891 if (!VI || VI.getSummaryList().empty()) {
4892 // Only declarations should not have a summary (a declaration might
4893 // however have a summary if the def was in module level asm).
4894 assert(F.isDeclaration());
4895 continue;
4896 }
4897 auto *Summary = VI.getSummaryList()[0].get();
4898 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4900 FS, /*GetStackIndex*/ [](unsigned I) { return I; }, CallStacks);
4901 }
4902 // Finalize the radix tree, write it out, and get the map of positions in the
4903 // linearized tree array.
4904 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
4905 if (!CallStacks.empty()) {
4906 CallStackPos =
4907 writeMemoryProfileRadixTree(std::move(CallStacks), Stream, RadixAbbrev);
4908 }
4909
4910 // Keep track of the current index into the CallStackPos map.
4911 CallStackId CallStackCount = 0;
4912
4913 SmallVector<uint64_t, 64> NameVals;
4914 // Iterate over the list of functions instead of the Index to
4915 // ensure the ordering is stable.
4916 for (const Function &F : M) {
4917 // Summary emission does not support anonymous functions, they have to
4918 // renamed using the anonymous function renaming pass.
4919 if (!F.hasName())
4920 report_fatal_error("Unexpected anonymous function when writing summary");
4921
4922 ValueInfo VI = Index->getValueInfo(F.getGUID());
4923 if (!VI || VI.getSummaryList().empty()) {
4924 // Only declarations should not have a summary (a declaration might
4925 // however have a summary if the def was in module level asm).
4926 assert(F.isDeclaration());
4927 continue;
4928 }
4929 auto *Summary = VI.getSummaryList()[0].get();
4930 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
4931 FSCallsProfileAbbrev, CallsiteAbbrev,
4932 AllocAbbrev, ContextIdAbbvId, F,
4933 CallStackPos, CallStackCount);
4934 }
4935
4936 // Capture references from GlobalVariable initializers, which are outside
4937 // of a function scope.
4938 for (const GlobalVariable &G : M.globals())
4939 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4940 FSModVTableRefsAbbrev);
4941
4942 for (const GlobalAlias &A : M.aliases()) {
4943 auto *Aliasee = A.getAliaseeObject();
4944 // Skip ifunc and nameless functions which don't have an entry in the
4945 // summary.
4946 if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
4947 continue;
4948 auto AliasId = VE.getValueID(&A);
4949 auto AliaseeId = VE.getValueID(Aliasee);
4950 NameVals.push_back(AliasId);
4951 auto *Summary = Index->getGlobalValueSummary(A);
4952 AliasSummary *AS = cast<AliasSummary>(Summary);
4953 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4954 NameVals.push_back(AliaseeId);
4955 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4956 NameVals.clear();
4957 }
4958
4959 for (auto &S : Index->typeIdCompatibleVtableMap()) {
4960 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4961 S.second, VE);
4962 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4963 TypeIdCompatibleVtableAbbrev);
4964 NameVals.clear();
4965 }
4966
4967 if (Index->getBlockCount())
4969 ArrayRef<uint64_t>{Index->getBlockCount()});
4970
4971 Stream.ExitBlock();
4972}
4973
4974/// Emit the combined summary section into the combined index file.
4975void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4977 Stream.EmitRecord(
4979 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
4980
4981 // Write the index flags.
4982 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
4983
4984 auto Abbv = std::make_shared<BitCodeAbbrev>();
4985 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID));
4986 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4987 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
4988 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4989 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4990 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4991
4992 for (const auto &GVI : valueIds()) {
4994 ArrayRef<uint32_t>{GVI.second,
4995 static_cast<uint32_t>(GVI.first >> 32),
4996 static_cast<uint32_t>(GVI.first)},
4997 ValueGuidAbbrev);
4998 }
4999
5000 // Write the stack ids used by this index, which will be a subset of those in
5001 // the full index in the case of distributed indexes.
5002 if (!StackIds.empty()) {
5003 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5004 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
5005 // numids x stackid
5006 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5007 // The stack ids are hashes that are close to 64 bits in size, so emitting
5008 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
5009 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
5010 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
5011 SmallVector<uint32_t> Vals;
5012 Vals.reserve(StackIds.size() * 2);
5013 for (auto Id : StackIds) {
5014 Vals.push_back(static_cast<uint32_t>(Id >> 32));
5015 Vals.push_back(static_cast<uint32_t>(Id));
5016 }
5017 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
5018 }
5019
5020 // Abbrev for FS_COMBINED_PROFILE.
5021 Abbv = std::make_shared<BitCodeAbbrev>();
5022 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
5023 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5024 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
5025 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5026 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
5027 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
5028 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
5029 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
5030 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
5031 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
5032 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
5033 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5034 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5035 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5036
5037 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
5038 Abbv = std::make_shared<BitCodeAbbrev>();
5039 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
5040 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5041 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
5042 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5043 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
5044 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5045 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5046
5047 // Abbrev for FS_COMBINED_ALIAS.
5048 Abbv = std::make_shared<BitCodeAbbrev>();
5049 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
5050 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5051 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
5052 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5053 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5054 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5055
5056 Abbv = std::make_shared<BitCodeAbbrev>();
5057 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_CALLSITE_INFO));
5058 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5059 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices
5060 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
5061 // numstackindices x stackidindex, numver x version
5062 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5063 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5064 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5065
5066 Abbv = std::make_shared<BitCodeAbbrev>();
5067 Abbv->Add(BitCodeAbbrevOp(CombinedIndexMemProfContext
5070 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
5071 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
5072 // nummib x (alloc type, context radix tree index),
5073 // numver x version
5074 // optional: nummib x total size
5075 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5076 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5077 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5078
5079 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) -> bool {
5080 if (DecSummaries == nullptr)
5081 return false;
5082 return DecSummaries->count(GVS);
5083 };
5084
5085 // The aliases are emitted as a post-pass, and will point to the value
5086 // id of the aliasee. Save them in a vector for post-processing.
5088
5089 // Save the value id for each summary for alias emission.
5090 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5091
5092 SmallVector<uint64_t, 64> NameVals;
5093
5094 // Set that will be populated during call to writeFunctionTypeMetadataRecords
5095 // with the type ids referenced by this index file.
5096 std::set<GlobalValue::GUID> ReferencedTypeIds;
5097
5098 // For local linkage, we also emit the original name separately
5099 // immediately after the record.
5100 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5101 // We don't need to emit the original name if we are writing the index for
5102 // distributed backends (in which case ModuleToSummariesForIndex is
5103 // non-null). The original name is only needed during the thin link, since
5104 // for SamplePGO the indirect call targets for local functions have
5105 // have the original name annotated in profile.
5106 // Continue to emit it when writing out the entire combined index, which is
5107 // used in testing the thin link via llvm-lto.
5108 if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
5109 return;
5110 NameVals.push_back(S.getOriginalName());
5112 NameVals.clear();
5113 };
5114
5115 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5117 Abbv = std::make_shared<BitCodeAbbrev>();
5118 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CONTEXT_RADIX_TREE_ARRAY));
5119 // n x entry
5120 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5121 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5122 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5123
5124 // First walk through all the functions and collect the allocation contexts
5125 // in their associated summaries, for use in constructing a radix tree of
5126 // contexts. Note that we need to do this in the same order as the functions
5127 // are processed further below since the call stack positions in the
5128 // resulting radix tree array are identified based on this order.
5129 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5130 forEachSummary([&](GVInfo I, bool IsAliasee) {
5131 // Don't collect this when invoked for an aliasee, as it is not needed for
5132 // the alias summary. If the aliasee is to be imported, we will invoke
5133 // this separately with IsAliasee=false.
5134 if (IsAliasee)
5135 return;
5136 GlobalValueSummary *S = I.second;
5137 assert(S);
5138 auto *FS = dyn_cast<FunctionSummary>(S);
5139 if (!FS)
5140 return;
5142 FS,
5143 /*GetStackIndex*/
5144 [&](unsigned I) {
5145 // Get the corresponding index into the list of StackIds actually
5146 // being written for this combined index (which may be a subset in
5147 // the case of distributed indexes).
5148 assert(StackIdIndicesToIndex.contains(I));
5149 return StackIdIndicesToIndex[I];
5150 },
5151 CallStacks);
5152 });
5153 // Finalize the radix tree, write it out, and get the map of positions in
5154 // the linearized tree array.
5155 if (!CallStacks.empty()) {
5156 CallStackPos = writeMemoryProfileRadixTree(std::move(CallStacks), Stream,
5157 RadixAbbrev);
5158 }
5159 }
5160
5161 // Keep track of the current index into the CallStackPos map. Not used if
5162 // CombinedIndexMemProfContext is false.
5163 CallStackId CallStackCount = 0;
5164
5165 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5166 forEachSummary([&](GVInfo I, bool IsAliasee) {
5167 GlobalValueSummary *S = I.second;
5168 assert(S);
5169 DefOrUseGUIDs.insert(I.first);
5170 for (const ValueInfo &VI : S->refs())
5171 DefOrUseGUIDs.insert(VI.getGUID());
5172
5173 auto ValueId = getValueId(I.first);
5174 assert(ValueId);
5175 SummaryToValueIdMap[S] = *ValueId;
5176
5177 // If this is invoked for an aliasee, we want to record the above
5178 // mapping, but then not emit a summary entry (if the aliasee is
5179 // to be imported, we will invoke this separately with IsAliasee=false).
5180 if (IsAliasee)
5181 return;
5182
5183 if (auto *AS = dyn_cast<AliasSummary>(S)) {
5184 // Will process aliases as a post-pass because the reader wants all
5185 // global to be loaded first.
5186 Aliases.push_back(AS);
5187 return;
5188 }
5189
5190 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
5191 NameVals.push_back(*ValueId);
5192 assert(ModuleIdMap.count(VS->modulePath()));
5193 NameVals.push_back(ModuleIdMap[VS->modulePath()]);
5194 NameVals.push_back(
5195 getEncodedGVSummaryFlags(VS->flags(), shouldImportValueAsDecl(VS)));
5196 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
5197 for (auto &RI : VS->refs()) {
5198 auto RefValueId = getValueId(RI.getGUID());
5199 if (!RefValueId)
5200 continue;
5201 NameVals.push_back(*RefValueId);
5202 }
5203
5204 // Emit the finished record.
5206 FSModRefsAbbrev);
5207 NameVals.clear();
5208 MaybeEmitOriginalName(*S);
5209 return;
5210 }
5211
5212 auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> {
5213 if (!VI)
5214 return std::nullopt;
5215 return getValueId(VI.getGUID());
5216 };
5217
5218 auto *FS = cast<FunctionSummary>(S);
5219 writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
5220 getReferencedTypeIds(FS, ReferencedTypeIds);
5221
5222 NameVals.push_back(*ValueId);
5223 assert(ModuleIdMap.count(FS->modulePath()));
5224 NameVals.push_back(ModuleIdMap[FS->modulePath()]);
5225 NameVals.push_back(
5226 getEncodedGVSummaryFlags(FS->flags(), shouldImportValueAsDecl(FS)));
5227 NameVals.push_back(FS->instCount());
5228 NameVals.push_back(getEncodedFFlags(FS->fflags()));
5229 // TODO: Stop writing entry count and bump bitcode version.
5230 NameVals.push_back(0 /* EntryCount */);
5231
5232 // Fill in below
5233 NameVals.push_back(0); // numrefs
5234 NameVals.push_back(0); // rorefcnt
5235 NameVals.push_back(0); // worefcnt
5236
5237 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5238 for (auto &RI : FS->refs()) {
5239 auto RefValueId = getValueId(RI.getGUID());
5240 if (!RefValueId)
5241 continue;
5242 NameVals.push_back(*RefValueId);
5243 if (RI.isReadOnly())
5244 RORefCnt++;
5245 else if (RI.isWriteOnly())
5246 WORefCnt++;
5247 Count++;
5248 }
5249 NameVals[6] = Count;
5250 NameVals[7] = RORefCnt;
5251 NameVals[8] = WORefCnt;
5252
5253 for (auto &EI : FS->calls()) {
5254 // If this GUID doesn't have a value id, it doesn't have a function
5255 // summary and we don't need to record any calls to it.
5256 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5257 if (!CallValueId)
5258 continue;
5259 NameVals.push_back(*CallValueId);
5260 NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second));
5261 }
5262
5263 // Emit the finished record.
5264 Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals,
5265 FSCallsProfileAbbrev);
5266 NameVals.clear();
5267
5269 Stream, FS, CallsiteAbbrev, AllocAbbrev, /*ContextIdAbbvId*/ 0,
5270 /*PerModule*/ false,
5271 /*GetValueId*/
5272 [&](const ValueInfo &VI) -> unsigned {
5273 std::optional<unsigned> ValueID = GetValueId(VI);
5274 // This can happen in shared index files for distributed ThinLTO if
5275 // the callee function summary is not included. Record 0 which we
5276 // will have to deal with conservatively when doing any kind of
5277 // validation in the ThinLTO backends.
5278 if (!ValueID)
5279 return 0;
5280 return *ValueID;
5281 },
5282 /*GetStackIndex*/
5283 [&](unsigned I) {
5284 // Get the corresponding index into the list of StackIds actually
5285 // being written for this combined index (which may be a subset in
5286 // the case of distributed indexes).
5287 assert(StackIdIndicesToIndex.contains(I));
5288 return StackIdIndicesToIndex[I];
5289 },
5290 /*WriteContextSizeInfoIndex*/ false, CallStackPos, CallStackCount);
5291
5292 MaybeEmitOriginalName(*S);
5293 });
5294
5295 for (auto *AS : Aliases) {
5296 auto AliasValueId = SummaryToValueIdMap[AS];
5297 assert(AliasValueId);
5298 NameVals.push_back(AliasValueId);
5299 assert(ModuleIdMap.count(AS->modulePath()));
5300 NameVals.push_back(ModuleIdMap[AS->modulePath()]);
5301 NameVals.push_back(
5302 getEncodedGVSummaryFlags(AS->flags(), shouldImportValueAsDecl(AS)));
5303 // Set value id to 0 when an alias is imported but the aliasee summary is
5304 // not contained in the index.
5305 auto AliaseeValueId =
5306 AS->hasAliasee() ? SummaryToValueIdMap[&AS->getAliasee()] : 0;
5307 NameVals.push_back(AliaseeValueId);
5308
5309 // Emit the finished record.
5310 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
5311 NameVals.clear();
5312 MaybeEmitOriginalName(*AS);
5313
5314 if (AS->hasAliasee())
5315 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
5316 getReferencedTypeIds(FS, ReferencedTypeIds);
5317 }
5318
5319 SmallVector<StringRef, 4> Functions;
5320 auto EmitCfiFunctions = [&](const CfiFunctionIndex &CfiIndex,
5322 if (CfiIndex.empty())
5323 return;
5324 for (GlobalValue::GUID GUID : DefOrUseGUIDs) {
5325 auto Defs = CfiIndex.forGuid(GUID);
5326 llvm::append_range(Functions, Defs);
5327 }
5328 if (Functions.empty())
5329 return;
5330 llvm::sort(Functions);
5331 for (const auto &S : Functions) {
5332 NameVals.push_back(StrtabBuilder.add(S));
5333 NameVals.push_back(S.size());
5334 }
5335 Stream.EmitRecord(Code, NameVals);
5336 NameVals.clear();
5337 Functions.clear();
5338 };
5339
5340 EmitCfiFunctions(Index.cfiFunctionDefs(), bitc::FS_CFI_FUNCTION_DEFS);
5341 EmitCfiFunctions(Index.cfiFunctionDecls(), bitc::FS_CFI_FUNCTION_DECLS);
5342
5343 // Walk the GUIDs that were referenced, and write the
5344 // corresponding type id records.
5345 for (auto &T : ReferencedTypeIds) {
5346 auto TidIter = Index.typeIds().equal_range(T);
5347 for (const auto &[GUID, TypeIdPair] : make_range(TidIter)) {
5348 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, TypeIdPair.first,
5349 TypeIdPair.second);
5350 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
5351 NameVals.clear();
5352 }
5353 }
5354
5355 if (Index.getBlockCount())
5357 ArrayRef<uint64_t>{Index.getBlockCount()});
5358
5359 Stream.ExitBlock();
5360}
5361
5362/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
5363/// current llvm version, and a record for the epoch number.
5366
5367 // Write the "user readable" string identifying the bitcode producer
5368 auto Abbv = std::make_shared<BitCodeAbbrev>();
5372 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5374 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5375
5376 // Write the epoch version
5377 Abbv = std::make_shared<BitCodeAbbrev>();
5380 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5381 constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
5382 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
5383 Stream.ExitBlock();
5384}
5385
5386void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5387 // Emit the module's hash.
5388 // MODULE_CODE_HASH: [5*i32]
5389 if (GenerateHash) {
5390 uint32_t Vals[5];
5391 Hasher.update(ArrayRef<uint8_t>(
5392 reinterpret_cast<const uint8_t *>(View.data()), View.size()));
5393 std::array<uint8_t, 20> Hash = Hasher.result();
5394 for (int Pos = 0; Pos < 20; Pos += 4) {
5395 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
5396 }
5397
5398 // Emit the finished record.
5399 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
5400
5401 if (ModHash)
5402 // Save the written hash value.
5403 llvm::copy(Vals, std::begin(*ModHash));
5404 }
5405}
5406
5407void ModuleBitcodeWriter::write() {
5409
5411 // We will want to write the module hash at this point. Block any flushing so
5412 // we can have access to the whole underlying data later.
5413 Stream.markAndBlockFlushing();
5414
5415 writeModuleVersion();
5416
5417 // Emit blockinfo, which defines the standard abbreviations etc.
5418 writeBlockInfo();
5419
5420 // Emit information describing all of the types in the module.
5421 writeTypeTable();
5422
5423 // Emit information about attribute groups.
5424 writeAttributeGroupTable();
5425
5426 // Emit information about parameter attributes.
5427 writeAttributeTable();
5428
5429 writeComdats();
5430
5431 // Emit top-level description of module, including target triple, inline asm,
5432 // descriptors for global variables, and function prototype info.
5433 writeModuleInfo();
5434
5435 // Emit constants.
5436 writeModuleConstants();
5437
5438 // Emit metadata kind names.
5439 writeModuleMetadataKinds();
5440
5441 // Emit metadata.
5442 writeModuleMetadata();
5443
5444 // Emit module-level use-lists.
5446 writeUseListBlock(nullptr);
5447
5448 writeOperandBundleTags();
5449 writeSyncScopeNames();
5450
5451 // Emit function bodies.
5452 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5453 for (const Function &F : M)
5454 if (!F.isDeclaration())
5455 writeFunction(F, FunctionToBitcodeIndex);
5456
5457 // Need to write after the above call to WriteFunction which populates
5458 // the summary information in the index.
5459 if (Index)
5460 writePerModuleGlobalValueSummary();
5461
5462 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5463
5464 writeModuleHash(Stream.getMarkedBufferAndResumeFlushing());
5465
5466 Stream.ExitBlock();
5467}
5468
5470 uint32_t &Position) {
5471 support::endian::write32le(&Buffer[Position], Value);
5472 Position += 4;
5473}
5474
5475/// If generating a bc file on darwin, we have to emit a
5476/// header and trailer to make it compatible with the system archiver. To do
5477/// this we emit the following header, and then emit a trailer that pads the
5478/// file out to be a multiple of 16 bytes.
5479///
5480/// struct bc_header {
5481/// uint32_t Magic; // 0x0B17C0DE
5482/// uint32_t Version; // Version, currently always 0.
5483/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
5484/// uint32_t BitcodeSize; // Size of traditional bitcode file.
5485/// uint32_t CPUType; // CPU specifier.
5486/// ... potentially more later ...
5487/// };
5489 const Triple &TT) {
5490 unsigned CPUType = ~0U;
5491
5492 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
5493 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
5494 // number from /usr/include/mach/machine.h. It is ok to reproduce the
5495 // specific constants here because they are implicitly part of the Darwin ABI.
5496 enum {
5497 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5498 DARWIN_CPU_TYPE_X86 = 7,
5499 DARWIN_CPU_TYPE_ARM = 12,
5500 DARWIN_CPU_TYPE_POWERPC = 18
5501 };
5502
5503 Triple::ArchType Arch = TT.getArch();
5504 if (Arch == Triple::x86_64)
5505 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5506 else if (Arch == Triple::x86)
5507 CPUType = DARWIN_CPU_TYPE_X86;
5508 else if (Arch == Triple::ppc)
5509 CPUType = DARWIN_CPU_TYPE_POWERPC;
5510 else if (Arch == Triple::ppc64)
5511 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5512 else if (Arch == Triple::arm || Arch == Triple::thumb)
5513 CPUType = DARWIN_CPU_TYPE_ARM;
5514
5515 // Traditional Bitcode starts after header.
5516 assert(Buffer.size() >= BWH_HeaderSize &&
5517 "Expected header size to be reserved");
5518 unsigned BCOffset = BWH_HeaderSize;
5519 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
5520
5521 // Write the magic and version.
5522 unsigned Position = 0;
5523 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
5524 writeInt32ToBuffer(0, Buffer, Position); // Version.
5525 writeInt32ToBuffer(BCOffset, Buffer, Position);
5526 writeInt32ToBuffer(BCSize, Buffer, Position);
5527 writeInt32ToBuffer(CPUType, Buffer, Position);
5528
5529 // If the file is not a multiple of 16 bytes, insert dummy padding.
5530 while (Buffer.size() & 15)
5531 Buffer.push_back(0);
5532}
5533
5534/// Helper to write the header common to all bitcode files.
5536 // Emit the file header.
5537 Stream.Emit((unsigned)'B', 8);
5538 Stream.Emit((unsigned)'C', 8);
5539 Stream.Emit(0x0, 4);
5540 Stream.Emit(0xC, 4);
5541 Stream.Emit(0xE, 4);
5542 Stream.Emit(0xD, 4);
5543}
5544
5546 : Stream(new BitstreamWriter(Buffer)) {
5547 writeBitcodeHeader(*Stream);
5548}
5549
5554
5556
5557void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
5558 Stream->EnterSubblock(Block, 3);
5559
5560 auto Abbv = std::make_shared<BitCodeAbbrev>();
5561 Abbv->Add(BitCodeAbbrevOp(Record));
5563 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
5564
5565 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
5566
5567 Stream->ExitBlock();
5568}
5569
5571 assert(!WroteStrtab && !WroteSymtab);
5572
5573 // If any module has module-level inline asm, we will require a registered asm
5574 // parser for the target so that we can create an accurate symbol table for
5575 // the module.
5576 for (Module *M : Mods) {
5577 if (M->getModuleInlineAsm().empty())
5578 continue;
5579
5580 std::string Err;
5581 const Triple TT(M->getTargetTriple());
5582 const Target *T = TargetRegistry::lookupTarget(TT, Err);
5583 if (!T || !T->hasMCAsmParser())
5584 return;
5585 }
5586
5587 WroteSymtab = true;
5588 SmallVector<char, 0> Symtab;
5589 // The irsymtab::build function may be unable to create a symbol table if the
5590 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
5591 // table is not required for correctness, but we still want to be able to
5592 // write malformed modules to bitcode files, so swallow the error.
5593 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
5594 consumeError(std::move(E));
5595 return;
5596 }
5597
5599 {Symtab.data(), Symtab.size()});
5600}
5601
5603 assert(!WroteStrtab);
5604
5605 std::vector<char> Strtab;
5606 StrtabBuilder.finalizeInOrder();
5607 Strtab.resize(StrtabBuilder.getSize());
5608 StrtabBuilder.write((uint8_t *)Strtab.data());
5609
5611 {Strtab.data(), Strtab.size()});
5612
5613 WroteStrtab = true;
5614}
5615
5617 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
5618 WroteStrtab = true;
5619}
5620
5622 bool ShouldPreserveUseListOrder,
5623 const ModuleSummaryIndex *Index,
5624 bool GenerateHash, ModuleHash *ModHash) {
5625 assert(!WroteStrtab);
5626
5627 // The Mods vector is used by irsymtab::build, which requires non-const
5628 // Modules in case it needs to materialize metadata. But the bitcode writer
5629 // requires that the module is materialized, so we can cast to non-const here,
5630 // after checking that it is in fact materialized.
5631 assert(M.isMaterialized());
5632 Mods.push_back(const_cast<Module *>(&M));
5633
5634 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5635 ShouldPreserveUseListOrder, Index,
5636 GenerateHash, ModHash);
5637 ModuleWriter.write();
5638}
5639
5641 const ModuleSummaryIndex *Index,
5642 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5643 const GVSummaryPtrSet *DecSummaries) {
5644 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5645 ModuleToSummariesForIndex);
5646 IndexWriter.write();
5647}
5648
5649/// Write the specified module to the specified output stream.
5651 bool ShouldPreserveUseListOrder,
5652 const ModuleSummaryIndex *Index,
5653 bool GenerateHash, ModuleHash *ModHash) {
5654 auto Write = [&](BitcodeWriter &Writer) {
5655 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5656 ModHash);
5657 Writer.writeSymtab();
5658 Writer.writeStrtab();
5659 };
5660 Triple TT(M.getTargetTriple());
5661 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5662 // If this is darwin or another generic macho target, reserve space for the
5663 // header. Note that the header is computed *after* the output is known, so
5664 // we currently explicitly use a buffer, write to it, and then subsequently
5665 // flush to Out.
5666 SmallVector<char, 0> Buffer;
5667 Buffer.reserve(256 * 1024);
5668 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
5669 BitcodeWriter Writer(Buffer);
5670 Write(Writer);
5671 emitDarwinBCHeaderAndTrailer(Buffer, TT);
5672 Out.write(Buffer.data(), Buffer.size());
5673 } else {
5674 BitcodeWriter Writer(Out);
5675 Write(Writer);
5676 }
5677}
5678
5679void IndexBitcodeWriter::write() {
5681
5682 writeModuleVersion();
5683
5684 // Write the module paths in the combined index.
5685 writeModStrings();
5686
5687 // Write the summary combined index records.
5688 writeCombinedGlobalValueSummary();
5689
5690 Stream.ExitBlock();
5691}
5692
5693// Write the specified module summary index to the given raw output stream,
5694// where it will be written in a new bitcode block. This is used when
5695// writing the combined index file for ThinLTO. When writing a subset of the
5696// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
5698 const ModuleSummaryIndex &Index, raw_ostream &Out,
5699 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5700 const GVSummaryPtrSet *DecSummaries) {
5701 SmallVector<char, 0> Buffer;
5702 Buffer.reserve(256 * 1024);
5703
5704 BitcodeWriter Writer(Buffer);
5705 Writer.writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5706 Writer.writeStrtab();
5707
5708 Out.write((char *)&Buffer.front(), Buffer.size());
5709}
5710
5711namespace {
5712
5713/// Class to manage the bitcode writing for a thin link bitcode file.
5714class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
5715 /// ModHash is for use in ThinLTO incremental build, generated while writing
5716 /// the module bitcode file.
5717 const ModuleHash *ModHash;
5718
5719public:
5720 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
5721 BitstreamWriter &Stream,
5722 const ModuleSummaryIndex &Index,
5723 const ModuleHash &ModHash)
5724 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5725 /*ShouldPreserveUseListOrder=*/false, &Index),
5726 ModHash(&ModHash) {}
5727
5728 void write();
5729
5730private:
5731 void writeSimplifiedModuleInfo();
5732};
5733
5734} // end anonymous namespace
5735
5736// This function writes a simpilified module info for thin link bitcode file.
5737// It only contains the source file name along with the name(the offset and
5738// size in strtab) and linkage for global values. For the global value info
5739// entry, in order to keep linkage at offset 5, there are three zeros used
5740// as padding.
5741void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5743 // Emit the module's source file name.
5744 {
5745 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
5747 if (Bits == SE_Char6)
5748 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
5749 else if (Bits == SE_Fixed7)
5750 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
5751
5752 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5753 auto Abbv = std::make_shared<BitCodeAbbrev>();
5756 Abbv->Add(AbbrevOpToUse);
5757 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5758
5759 for (const auto P : M.getSourceFileName())
5760 Vals.push_back((unsigned char)P);
5761
5762 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
5763 Vals.clear();
5764 }
5765
5766 // Emit the global variable information.
5767 for (const GlobalVariable &GV : M.globals()) {
5768 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
5769 Vals.push_back(StrtabBuilder.add(GV.getName()));
5770 Vals.push_back(GV.getName().size());
5771 Vals.push_back(0);
5772 Vals.push_back(0);
5773 Vals.push_back(0);
5774 Vals.push_back(getEncodedLinkage(GV));
5775
5777 Vals.clear();
5778 }
5779
5780 // Emit the function proto information.
5781 for (const Function &F : M) {
5782 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
5783 Vals.push_back(StrtabBuilder.add(F.getName()));
5784 Vals.push_back(F.getName().size());
5785 Vals.push_back(0);
5786 Vals.push_back(0);
5787 Vals.push_back(0);
5789
5791 Vals.clear();
5792 }
5793
5794 // Emit the alias information.
5795 for (const GlobalAlias &A : M.aliases()) {
5796 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
5797 Vals.push_back(StrtabBuilder.add(A.getName()));
5798 Vals.push_back(A.getName().size());
5799 Vals.push_back(0);
5800 Vals.push_back(0);
5801 Vals.push_back(0);
5803
5804 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
5805 Vals.clear();
5806 }
5807
5808 // Emit the ifunc information.
5809 for (const GlobalIFunc &I : M.ifuncs()) {
5810 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
5811 Vals.push_back(StrtabBuilder.add(I.getName()));
5812 Vals.push_back(I.getName().size());
5813 Vals.push_back(0);
5814 Vals.push_back(0);
5815 Vals.push_back(0);
5817
5818 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
5819 Vals.clear();
5820 }
5821}
5822
5823void ThinLinkBitcodeWriter::write() {
5825
5826 writeModuleVersion();
5827
5828 writeSimplifiedModuleInfo();
5829
5830 writePerModuleGlobalValueSummary();
5831
5832 // Write module hash.
5834
5835 Stream.ExitBlock();
5836}
5837
5839 const ModuleSummaryIndex &Index,
5840 const ModuleHash &ModHash) {
5841 assert(!WroteStrtab);
5842
5843 // The Mods vector is used by irsymtab::build, which requires non-const
5844 // Modules in case it needs to materialize metadata. But the bitcode writer
5845 // requires that the module is materialized, so we can cast to non-const here,
5846 // after checking that it is in fact materialized.
5847 assert(M.isMaterialized());
5848 Mods.push_back(const_cast<Module *>(&M));
5849
5850 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
5851 ModHash);
5852 ThinLinkWriter.write();
5853}
5854
5855// Write the specified thin link bitcode file to the given raw output stream,
5856// where it will be written in a new bitcode block. This is used when
5857// writing the per-module index file for ThinLTO.
5859 const ModuleSummaryIndex &Index,
5860 const ModuleHash &ModHash) {
5861 SmallVector<char, 0> Buffer;
5862 Buffer.reserve(256 * 1024);
5863
5864 BitcodeWriter Writer(Buffer);
5865 Writer.writeThinLinkBitcode(M, Index, ModHash);
5866 Writer.writeSymtab();
5867 Writer.writeStrtab();
5868
5869 Out.write((char *)&Buffer.front(), Buffer.size());
5870}
5871
5872static const char *getSectionNameForBitcode(const Triple &T) {
5873 switch (T.getObjectFormat()) {
5874 case Triple::MachO:
5875 return "__LLVM,__bitcode";
5876 case Triple::COFF:
5877 case Triple::ELF:
5878 case Triple::Wasm:
5880 return ".llvmbc";
5881 case Triple::GOFF:
5882 llvm_unreachable("GOFF is not yet implemented");
5883 break;
5884 case Triple::SPIRV:
5885 if (T.getVendor() == Triple::AMD)
5886 return ".llvmbc";
5887 llvm_unreachable("SPIRV is not yet implemented");
5888 break;
5889 case Triple::XCOFF:
5890 llvm_unreachable("XCOFF is not yet implemented");
5891 break;
5893 llvm_unreachable("DXContainer is not yet implemented");
5894 break;
5895 }
5896 llvm_unreachable("Unimplemented ObjectFormatType");
5897}
5898
5899static const char *getSectionNameForCommandline(const Triple &T) {
5900 switch (T.getObjectFormat()) {
5901 case Triple::MachO:
5902 return "__LLVM,__cmdline";
5903 case Triple::COFF:
5904 case Triple::ELF:
5905 case Triple::Wasm:
5907 return ".llvmcmd";
5908 case Triple::GOFF:
5909 llvm_unreachable("GOFF is not yet implemented");
5910 break;
5911 case Triple::SPIRV:
5912 if (T.getVendor() == Triple::AMD)
5913 return ".llvmcmd";
5914 llvm_unreachable("SPIRV is not yet implemented");
5915 break;
5916 case Triple::XCOFF:
5917 llvm_unreachable("XCOFF is not yet implemented");
5918 break;
5920 llvm_unreachable("DXC is not yet implemented");
5921 break;
5922 }
5923 llvm_unreachable("Unimplemented ObjectFormatType");
5924}
5925
5927 bool EmbedBitcode, bool EmbedCmdline,
5928 const std::vector<uint8_t> &CmdArgs) {
5929 // Save llvm.compiler.used and remove it.
5932 GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
5933 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
5934 : PointerType::getUnqual(M.getContext());
5935 for (auto *GV : UsedGlobals) {
5936 if (GV->getName() != "llvm.embedded.module" &&
5937 GV->getName() != "llvm.cmdline")
5938 UsedArray.push_back(
5940 }
5941 if (Used)
5942 Used->eraseFromParent();
5943
5944 // Embed the bitcode for the llvm module.
5945 std::string Data;
5946 ArrayRef<uint8_t> ModuleData;
5947 Triple T(M.getTargetTriple());
5948
5949 if (EmbedBitcode) {
5950 if (Buf.getBufferSize() == 0 ||
5951 !isBitcode((const unsigned char *)Buf.getBufferStart(),
5952 (const unsigned char *)Buf.getBufferEnd())) {
5953 // If the input is LLVM Assembly, bitcode is produced by serializing
5954 // the module. Use-lists order need to be preserved in this case.
5956 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
5957 ModuleData =
5958 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
5959 } else
5960 // If the input is LLVM bitcode, write the input byte stream directly.
5961 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
5962 Buf.getBufferSize());
5963 }
5964 llvm::Constant *ModuleConstant =
5965 llvm::ConstantDataArray::get(M.getContext(), ModuleData);
5967 M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
5968 ModuleConstant);
5970 // Set alignment to 1 to prevent padding between two contributions from input
5971 // sections after linking.
5972 GV->setAlignment(Align(1));
5973 UsedArray.push_back(
5975 if (llvm::GlobalVariable *Old =
5976 M.getGlobalVariable("llvm.embedded.module", true)) {
5977 assert(Old->hasZeroLiveUses() &&
5978 "llvm.embedded.module can only be used once in llvm.compiler.used");
5979 GV->takeName(Old);
5980 Old->eraseFromParent();
5981 } else {
5982 GV->setName("llvm.embedded.module");
5983 }
5984
5985 // Skip if only bitcode needs to be embedded.
5986 if (EmbedCmdline) {
5987 // Embed command-line options.
5988 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
5989 CmdArgs.size());
5990 llvm::Constant *CmdConstant =
5991 llvm::ConstantDataArray::get(M.getContext(), CmdData);
5992 GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
5994 CmdConstant);
5996 GV->setAlignment(Align(1));
5997 UsedArray.push_back(
5999 if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
6000 assert(Old->hasZeroLiveUses() &&
6001 "llvm.cmdline can only be used once in llvm.compiler.used");
6002 GV->takeName(Old);
6003 Old->eraseFromParent();
6004 } else {
6005 GV->setName("llvm.cmdline");
6006 }
6007 }
6008
6009 if (UsedArray.empty())
6010 return;
6011
6012 // Recreate llvm.compiler.used.
6013 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
6014 auto *NewUsed = new GlobalVariable(
6016 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
6017 NewUsed->setSection("llvm.metadata");
6018}
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
iterator_range< NestedIterator > forGuid(GlobalValue::GUID GUID) const
@ 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:114
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:174
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:169
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:239
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,...