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