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