10b57cec5SDimitry Andric //===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric
90b57cec5SDimitry Andric #include "MetadataLoader.h"
100b57cec5SDimitry Andric #include "ValueList.h"
110b57cec5SDimitry Andric
120b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
130b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
1481ad6265SDimitry Andric #include "llvm/ADT/BitmaskEnum.h"
150b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
160b57cec5SDimitry Andric #include "llvm/ADT/DenseSet.h"
1781ad6265SDimitry Andric #include "llvm/ADT/STLFunctionalExtras.h"
18fe013be4SDimitry Andric #include "llvm/ADT/SetVector.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
2081ad6265SDimitry Andric #include "llvm/ADT/SmallVector.h"
210b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
220b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
230b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
2481ad6265SDimitry Andric #include "llvm/ADT/ilist_iterator.h"
2581ad6265SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
260b57cec5SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
270b57cec5SDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h"
28349cc55cSDimitry Andric #include "llvm/Bitstream/BitstreamReader.h"
290b57cec5SDimitry Andric #include "llvm/IR/AutoUpgrade.h"
300b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
310b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
320b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
330b57cec5SDimitry Andric #include "llvm/IR/Function.h"
340b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
350b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
360b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
370b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
380b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
3981ad6265SDimitry Andric #include "llvm/IR/Metadata.h"
400b57cec5SDimitry Andric #include "llvm/IR/Module.h"
410b57cec5SDimitry Andric #include "llvm/IR/TrackingMDRef.h"
420b57cec5SDimitry Andric #include "llvm/IR/Type.h"
430b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
440b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
450b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
460b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
4781ad6265SDimitry Andric #include "llvm/Support/type_traits.h"
4881ad6265SDimitry Andric
490b57cec5SDimitry Andric #include <algorithm>
500b57cec5SDimitry Andric #include <cassert>
510b57cec5SDimitry Andric #include <cstddef>
520b57cec5SDimitry Andric #include <cstdint>
530b57cec5SDimitry Andric #include <deque>
5481ad6265SDimitry Andric #include <iterator>
550b57cec5SDimitry Andric #include <limits>
56fe013be4SDimitry Andric #include <map>
57bdd1243dSDimitry Andric #include <optional>
580b57cec5SDimitry Andric #include <string>
590b57cec5SDimitry Andric #include <tuple>
6081ad6265SDimitry Andric #include <type_traits>
610b57cec5SDimitry Andric #include <utility>
620b57cec5SDimitry Andric #include <vector>
6381ad6265SDimitry Andric namespace llvm {
6481ad6265SDimitry Andric class Argument;
6581ad6265SDimitry Andric }
660b57cec5SDimitry Andric
670b57cec5SDimitry Andric using namespace llvm;
680b57cec5SDimitry Andric
690b57cec5SDimitry Andric #define DEBUG_TYPE "bitcode-reader"
700b57cec5SDimitry Andric
710b57cec5SDimitry Andric STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
720b57cec5SDimitry Andric STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
730b57cec5SDimitry Andric STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
740b57cec5SDimitry Andric
750b57cec5SDimitry Andric /// Flag whether we need to import full type definitions for ThinLTO.
760b57cec5SDimitry Andric /// Currently needed for Darwin and LLDB.
770b57cec5SDimitry Andric static cl::opt<bool> ImportFullTypeDefinitions(
780b57cec5SDimitry Andric "import-full-type-definitions", cl::init(false), cl::Hidden,
790b57cec5SDimitry Andric cl::desc("Import full type definitions for ThinLTO."));
800b57cec5SDimitry Andric
810b57cec5SDimitry Andric static cl::opt<bool> DisableLazyLoading(
820b57cec5SDimitry Andric "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
830b57cec5SDimitry Andric cl::desc("Force disable the lazy-loading on-demand of metadata when "
840b57cec5SDimitry Andric "loading bitcode for importing."));
850b57cec5SDimitry Andric
860b57cec5SDimitry Andric namespace {
870b57cec5SDimitry Andric
unrotateSign(uint64_t U)880b57cec5SDimitry Andric static int64_t unrotateSign(uint64_t U) { return (U & 1) ? ~(U >> 1) : U >> 1; }
890b57cec5SDimitry Andric
900b57cec5SDimitry Andric class BitcodeReaderMetadataList {
910b57cec5SDimitry Andric /// Array of metadata references.
920b57cec5SDimitry Andric ///
930b57cec5SDimitry Andric /// Don't use std::vector here. Some versions of libc++ copy (instead of
940b57cec5SDimitry Andric /// move) on resize, and TrackingMDRef is very expensive to copy.
950b57cec5SDimitry Andric SmallVector<TrackingMDRef, 1> MetadataPtrs;
960b57cec5SDimitry Andric
970b57cec5SDimitry Andric /// The set of indices in MetadataPtrs above of forward references that were
980b57cec5SDimitry Andric /// generated.
990b57cec5SDimitry Andric SmallDenseSet<unsigned, 1> ForwardReference;
1000b57cec5SDimitry Andric
1010b57cec5SDimitry Andric /// The set of indices in MetadataPtrs above of Metadata that need to be
1020b57cec5SDimitry Andric /// resolved.
1030b57cec5SDimitry Andric SmallDenseSet<unsigned, 1> UnresolvedNodes;
1040b57cec5SDimitry Andric
1050b57cec5SDimitry Andric /// Structures for resolving old type refs.
1060b57cec5SDimitry Andric struct {
1070b57cec5SDimitry Andric SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
1080b57cec5SDimitry Andric SmallDenseMap<MDString *, DICompositeType *, 1> Final;
1090b57cec5SDimitry Andric SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
1100b57cec5SDimitry Andric SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
1110b57cec5SDimitry Andric } OldTypeRefs;
1120b57cec5SDimitry Andric
1130b57cec5SDimitry Andric LLVMContext &Context;
1140b57cec5SDimitry Andric
1150b57cec5SDimitry Andric /// Maximum number of valid references. Forward references exceeding the
1160b57cec5SDimitry Andric /// maximum must be invalid.
1170b57cec5SDimitry Andric unsigned RefsUpperBound;
1180b57cec5SDimitry Andric
1190b57cec5SDimitry Andric public:
BitcodeReaderMetadataList(LLVMContext & C,size_t RefsUpperBound)1200b57cec5SDimitry Andric BitcodeReaderMetadataList(LLVMContext &C, size_t RefsUpperBound)
1210b57cec5SDimitry Andric : Context(C),
1220b57cec5SDimitry Andric RefsUpperBound(std::min((size_t)std::numeric_limits<unsigned>::max(),
1230b57cec5SDimitry Andric RefsUpperBound)) {}
1240b57cec5SDimitry Andric
1250b57cec5SDimitry Andric // vector compatibility methods
size() const1260b57cec5SDimitry Andric unsigned size() const { return MetadataPtrs.size(); }
resize(unsigned N)1270b57cec5SDimitry Andric void resize(unsigned N) { MetadataPtrs.resize(N); }
push_back(Metadata * MD)1280b57cec5SDimitry Andric void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
clear()1290b57cec5SDimitry Andric void clear() { MetadataPtrs.clear(); }
back() const1300b57cec5SDimitry Andric Metadata *back() const { return MetadataPtrs.back(); }
pop_back()1310b57cec5SDimitry Andric void pop_back() { MetadataPtrs.pop_back(); }
empty() const1320b57cec5SDimitry Andric bool empty() const { return MetadataPtrs.empty(); }
1330b57cec5SDimitry Andric
operator [](unsigned i) const1340b57cec5SDimitry Andric Metadata *operator[](unsigned i) const {
1350b57cec5SDimitry Andric assert(i < MetadataPtrs.size());
1360b57cec5SDimitry Andric return MetadataPtrs[i];
1370b57cec5SDimitry Andric }
1380b57cec5SDimitry Andric
lookup(unsigned I) const1390b57cec5SDimitry Andric Metadata *lookup(unsigned I) const {
1400b57cec5SDimitry Andric if (I < MetadataPtrs.size())
1410b57cec5SDimitry Andric return MetadataPtrs[I];
1420b57cec5SDimitry Andric return nullptr;
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric
shrinkTo(unsigned N)1450b57cec5SDimitry Andric void shrinkTo(unsigned N) {
1460b57cec5SDimitry Andric assert(N <= size() && "Invalid shrinkTo request!");
1470b57cec5SDimitry Andric assert(ForwardReference.empty() && "Unexpected forward refs");
1480b57cec5SDimitry Andric assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
1490b57cec5SDimitry Andric MetadataPtrs.resize(N);
1500b57cec5SDimitry Andric }
1510b57cec5SDimitry Andric
1520b57cec5SDimitry Andric /// Return the given metadata, creating a replaceable forward reference if
1530b57cec5SDimitry Andric /// necessary.
1540b57cec5SDimitry Andric Metadata *getMetadataFwdRef(unsigned Idx);
1550b57cec5SDimitry Andric
1560b57cec5SDimitry Andric /// Return the given metadata only if it is fully resolved.
1570b57cec5SDimitry Andric ///
1580b57cec5SDimitry Andric /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
1590b57cec5SDimitry Andric /// would give \c false.
1600b57cec5SDimitry Andric Metadata *getMetadataIfResolved(unsigned Idx);
1610b57cec5SDimitry Andric
1620b57cec5SDimitry Andric MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
1630b57cec5SDimitry Andric void assignValue(Metadata *MD, unsigned Idx);
1640b57cec5SDimitry Andric void tryToResolveCycles();
hasFwdRefs() const1650b57cec5SDimitry Andric bool hasFwdRefs() const { return !ForwardReference.empty(); }
getNextFwdRef()1660b57cec5SDimitry Andric int getNextFwdRef() {
1670b57cec5SDimitry Andric assert(hasFwdRefs());
1680b57cec5SDimitry Andric return *ForwardReference.begin();
1690b57cec5SDimitry Andric }
1700b57cec5SDimitry Andric
1710b57cec5SDimitry Andric /// Upgrade a type that had an MDString reference.
1720b57cec5SDimitry Andric void addTypeRef(MDString &UUID, DICompositeType &CT);
1730b57cec5SDimitry Andric
1740b57cec5SDimitry Andric /// Upgrade a type that had an MDString reference.
1750b57cec5SDimitry Andric Metadata *upgradeTypeRef(Metadata *MaybeUUID);
1760b57cec5SDimitry Andric
1770b57cec5SDimitry Andric /// Upgrade a type ref array that may have MDString references.
1780b57cec5SDimitry Andric Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
1790b57cec5SDimitry Andric
1800b57cec5SDimitry Andric private:
1810b57cec5SDimitry Andric Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
1820b57cec5SDimitry Andric };
1830b57cec5SDimitry Andric
assignValue(Metadata * MD,unsigned Idx)1840b57cec5SDimitry Andric void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
1850b57cec5SDimitry Andric if (auto *MDN = dyn_cast<MDNode>(MD))
1860b57cec5SDimitry Andric if (!MDN->isResolved())
1870b57cec5SDimitry Andric UnresolvedNodes.insert(Idx);
1880b57cec5SDimitry Andric
1890b57cec5SDimitry Andric if (Idx == size()) {
1900b57cec5SDimitry Andric push_back(MD);
1910b57cec5SDimitry Andric return;
1920b57cec5SDimitry Andric }
1930b57cec5SDimitry Andric
1940b57cec5SDimitry Andric if (Idx >= size())
1950b57cec5SDimitry Andric resize(Idx + 1);
1960b57cec5SDimitry Andric
1970b57cec5SDimitry Andric TrackingMDRef &OldMD = MetadataPtrs[Idx];
1980b57cec5SDimitry Andric if (!OldMD) {
1990b57cec5SDimitry Andric OldMD.reset(MD);
2000b57cec5SDimitry Andric return;
2010b57cec5SDimitry Andric }
2020b57cec5SDimitry Andric
2030b57cec5SDimitry Andric // If there was a forward reference to this value, replace it.
2040b57cec5SDimitry Andric TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
2050b57cec5SDimitry Andric PrevMD->replaceAllUsesWith(MD);
2060b57cec5SDimitry Andric ForwardReference.erase(Idx);
2070b57cec5SDimitry Andric }
2080b57cec5SDimitry Andric
getMetadataFwdRef(unsigned Idx)2090b57cec5SDimitry Andric Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
2100b57cec5SDimitry Andric // Bail out for a clearly invalid value.
2110b57cec5SDimitry Andric if (Idx >= RefsUpperBound)
2120b57cec5SDimitry Andric return nullptr;
2130b57cec5SDimitry Andric
2140b57cec5SDimitry Andric if (Idx >= size())
2150b57cec5SDimitry Andric resize(Idx + 1);
2160b57cec5SDimitry Andric
2170b57cec5SDimitry Andric if (Metadata *MD = MetadataPtrs[Idx])
2180b57cec5SDimitry Andric return MD;
2190b57cec5SDimitry Andric
2200b57cec5SDimitry Andric // Track forward refs to be resolved later.
2210b57cec5SDimitry Andric ForwardReference.insert(Idx);
2220b57cec5SDimitry Andric
2230b57cec5SDimitry Andric // Create and return a placeholder, which will later be RAUW'd.
2240b57cec5SDimitry Andric ++NumMDNodeTemporary;
225bdd1243dSDimitry Andric Metadata *MD = MDNode::getTemporary(Context, std::nullopt).release();
2260b57cec5SDimitry Andric MetadataPtrs[Idx].reset(MD);
2270b57cec5SDimitry Andric return MD;
2280b57cec5SDimitry Andric }
2290b57cec5SDimitry Andric
getMetadataIfResolved(unsigned Idx)2300b57cec5SDimitry Andric Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
2310b57cec5SDimitry Andric Metadata *MD = lookup(Idx);
2320b57cec5SDimitry Andric if (auto *N = dyn_cast_or_null<MDNode>(MD))
2330b57cec5SDimitry Andric if (!N->isResolved())
2340b57cec5SDimitry Andric return nullptr;
2350b57cec5SDimitry Andric return MD;
2360b57cec5SDimitry Andric }
2370b57cec5SDimitry Andric
getMDNodeFwdRefOrNull(unsigned Idx)2380b57cec5SDimitry Andric MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
2390b57cec5SDimitry Andric return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
2400b57cec5SDimitry Andric }
2410b57cec5SDimitry Andric
tryToResolveCycles()2420b57cec5SDimitry Andric void BitcodeReaderMetadataList::tryToResolveCycles() {
2430b57cec5SDimitry Andric if (!ForwardReference.empty())
2440b57cec5SDimitry Andric // Still forward references... can't resolve cycles.
2450b57cec5SDimitry Andric return;
2460b57cec5SDimitry Andric
2470b57cec5SDimitry Andric // Give up on finding a full definition for any forward decls that remain.
2480b57cec5SDimitry Andric for (const auto &Ref : OldTypeRefs.FwdDecls)
2490b57cec5SDimitry Andric OldTypeRefs.Final.insert(Ref);
2500b57cec5SDimitry Andric OldTypeRefs.FwdDecls.clear();
2510b57cec5SDimitry Andric
2520b57cec5SDimitry Andric // Upgrade from old type ref arrays. In strange cases, this could add to
2530b57cec5SDimitry Andric // OldTypeRefs.Unknown.
2540b57cec5SDimitry Andric for (const auto &Array : OldTypeRefs.Arrays)
2550b57cec5SDimitry Andric Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
2560b57cec5SDimitry Andric OldTypeRefs.Arrays.clear();
2570b57cec5SDimitry Andric
2580b57cec5SDimitry Andric // Replace old string-based type refs with the resolved node, if possible.
2590b57cec5SDimitry Andric // If we haven't seen the node, leave it to the verifier to complain about
2600b57cec5SDimitry Andric // the invalid string reference.
2610b57cec5SDimitry Andric for (const auto &Ref : OldTypeRefs.Unknown) {
2620b57cec5SDimitry Andric if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
2630b57cec5SDimitry Andric Ref.second->replaceAllUsesWith(CT);
2640b57cec5SDimitry Andric else
2650b57cec5SDimitry Andric Ref.second->replaceAllUsesWith(Ref.first);
2660b57cec5SDimitry Andric }
2670b57cec5SDimitry Andric OldTypeRefs.Unknown.clear();
2680b57cec5SDimitry Andric
2690b57cec5SDimitry Andric if (UnresolvedNodes.empty())
2700b57cec5SDimitry Andric // Nothing to do.
2710b57cec5SDimitry Andric return;
2720b57cec5SDimitry Andric
2730b57cec5SDimitry Andric // Resolve any cycles.
2740b57cec5SDimitry Andric for (unsigned I : UnresolvedNodes) {
2750b57cec5SDimitry Andric auto &MD = MetadataPtrs[I];
2760b57cec5SDimitry Andric auto *N = dyn_cast_or_null<MDNode>(MD);
2770b57cec5SDimitry Andric if (!N)
2780b57cec5SDimitry Andric continue;
2790b57cec5SDimitry Andric
2800b57cec5SDimitry Andric assert(!N->isTemporary() && "Unexpected forward reference");
2810b57cec5SDimitry Andric N->resolveCycles();
2820b57cec5SDimitry Andric }
2830b57cec5SDimitry Andric
2840b57cec5SDimitry Andric // Make sure we return early again until there's another unresolved ref.
2850b57cec5SDimitry Andric UnresolvedNodes.clear();
2860b57cec5SDimitry Andric }
2870b57cec5SDimitry Andric
addTypeRef(MDString & UUID,DICompositeType & CT)2880b57cec5SDimitry Andric void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
2890b57cec5SDimitry Andric DICompositeType &CT) {
2900b57cec5SDimitry Andric assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
2910b57cec5SDimitry Andric if (CT.isForwardDecl())
2920b57cec5SDimitry Andric OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
2930b57cec5SDimitry Andric else
2940b57cec5SDimitry Andric OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
2950b57cec5SDimitry Andric }
2960b57cec5SDimitry Andric
upgradeTypeRef(Metadata * MaybeUUID)2970b57cec5SDimitry Andric Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
2980b57cec5SDimitry Andric auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
2990b57cec5SDimitry Andric if (LLVM_LIKELY(!UUID))
3000b57cec5SDimitry Andric return MaybeUUID;
3010b57cec5SDimitry Andric
3020b57cec5SDimitry Andric if (auto *CT = OldTypeRefs.Final.lookup(UUID))
3030b57cec5SDimitry Andric return CT;
3040b57cec5SDimitry Andric
3050b57cec5SDimitry Andric auto &Ref = OldTypeRefs.Unknown[UUID];
3060b57cec5SDimitry Andric if (!Ref)
307bdd1243dSDimitry Andric Ref = MDNode::getTemporary(Context, std::nullopt);
3080b57cec5SDimitry Andric return Ref.get();
3090b57cec5SDimitry Andric }
3100b57cec5SDimitry Andric
upgradeTypeRefArray(Metadata * MaybeTuple)3110b57cec5SDimitry Andric Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
3120b57cec5SDimitry Andric auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
3130b57cec5SDimitry Andric if (!Tuple || Tuple->isDistinct())
3140b57cec5SDimitry Andric return MaybeTuple;
3150b57cec5SDimitry Andric
3160b57cec5SDimitry Andric // Look through the array immediately if possible.
3170b57cec5SDimitry Andric if (!Tuple->isTemporary())
3180b57cec5SDimitry Andric return resolveTypeRefArray(Tuple);
3190b57cec5SDimitry Andric
3200b57cec5SDimitry Andric // Create and return a placeholder to use for now. Eventually
3210b57cec5SDimitry Andric // resolveTypeRefArrays() will be resolve this forward reference.
3220b57cec5SDimitry Andric OldTypeRefs.Arrays.emplace_back(
3230b57cec5SDimitry Andric std::piecewise_construct, std::forward_as_tuple(Tuple),
324bdd1243dSDimitry Andric std::forward_as_tuple(MDTuple::getTemporary(Context, std::nullopt)));
3250b57cec5SDimitry Andric return OldTypeRefs.Arrays.back().second.get();
3260b57cec5SDimitry Andric }
3270b57cec5SDimitry Andric
resolveTypeRefArray(Metadata * MaybeTuple)3280b57cec5SDimitry Andric Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
3290b57cec5SDimitry Andric auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
3300b57cec5SDimitry Andric if (!Tuple || Tuple->isDistinct())
3310b57cec5SDimitry Andric return MaybeTuple;
3320b57cec5SDimitry Andric
3330b57cec5SDimitry Andric // Look through the DITypeRefArray, upgrading each DIType *.
3340b57cec5SDimitry Andric SmallVector<Metadata *, 32> Ops;
3350b57cec5SDimitry Andric Ops.reserve(Tuple->getNumOperands());
3360b57cec5SDimitry Andric for (Metadata *MD : Tuple->operands())
3370b57cec5SDimitry Andric Ops.push_back(upgradeTypeRef(MD));
3380b57cec5SDimitry Andric
3390b57cec5SDimitry Andric return MDTuple::get(Context, Ops);
3400b57cec5SDimitry Andric }
3410b57cec5SDimitry Andric
3420b57cec5SDimitry Andric namespace {
3430b57cec5SDimitry Andric
3440b57cec5SDimitry Andric class PlaceholderQueue {
3450b57cec5SDimitry Andric // Placeholders would thrash around when moved, so store in a std::deque
3460b57cec5SDimitry Andric // instead of some sort of vector.
3470b57cec5SDimitry Andric std::deque<DistinctMDOperandPlaceholder> PHs;
3480b57cec5SDimitry Andric
3490b57cec5SDimitry Andric public:
~PlaceholderQueue()3500b57cec5SDimitry Andric ~PlaceholderQueue() {
351349cc55cSDimitry Andric assert(empty() &&
352349cc55cSDimitry Andric "PlaceholderQueue hasn't been flushed before being destroyed");
3530b57cec5SDimitry Andric }
empty() const354e8d8bef9SDimitry Andric bool empty() const { return PHs.empty(); }
3550b57cec5SDimitry Andric DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
3560b57cec5SDimitry Andric void flush(BitcodeReaderMetadataList &MetadataList);
3570b57cec5SDimitry Andric
3580b57cec5SDimitry Andric /// Return the list of temporaries nodes in the queue, these need to be
3590b57cec5SDimitry Andric /// loaded before we can flush the queue.
getTemporaries(BitcodeReaderMetadataList & MetadataList,DenseSet<unsigned> & Temporaries)3600b57cec5SDimitry Andric void getTemporaries(BitcodeReaderMetadataList &MetadataList,
3610b57cec5SDimitry Andric DenseSet<unsigned> &Temporaries) {
3620b57cec5SDimitry Andric for (auto &PH : PHs) {
3630b57cec5SDimitry Andric auto ID = PH.getID();
3640b57cec5SDimitry Andric auto *MD = MetadataList.lookup(ID);
3650b57cec5SDimitry Andric if (!MD) {
3660b57cec5SDimitry Andric Temporaries.insert(ID);
3670b57cec5SDimitry Andric continue;
3680b57cec5SDimitry Andric }
3690b57cec5SDimitry Andric auto *N = dyn_cast_or_null<MDNode>(MD);
3700b57cec5SDimitry Andric if (N && N->isTemporary())
3710b57cec5SDimitry Andric Temporaries.insert(ID);
3720b57cec5SDimitry Andric }
3730b57cec5SDimitry Andric }
3740b57cec5SDimitry Andric };
3750b57cec5SDimitry Andric
3760b57cec5SDimitry Andric } // end anonymous namespace
3770b57cec5SDimitry Andric
getPlaceholderOp(unsigned ID)3780b57cec5SDimitry Andric DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
3790b57cec5SDimitry Andric PHs.emplace_back(ID);
3800b57cec5SDimitry Andric return PHs.back();
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric
flush(BitcodeReaderMetadataList & MetadataList)3830b57cec5SDimitry Andric void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
3840b57cec5SDimitry Andric while (!PHs.empty()) {
3850b57cec5SDimitry Andric auto *MD = MetadataList.lookup(PHs.front().getID());
3860b57cec5SDimitry Andric assert(MD && "Flushing placeholder on unassigned MD");
3870b57cec5SDimitry Andric #ifndef NDEBUG
3880b57cec5SDimitry Andric if (auto *MDN = dyn_cast<MDNode>(MD))
3890b57cec5SDimitry Andric assert(MDN->isResolved() &&
3900b57cec5SDimitry Andric "Flushing Placeholder while cycles aren't resolved");
3910b57cec5SDimitry Andric #endif
3920b57cec5SDimitry Andric PHs.front().replaceUseWith(MD);
3930b57cec5SDimitry Andric PHs.pop_front();
3940b57cec5SDimitry Andric }
3950b57cec5SDimitry Andric }
3960b57cec5SDimitry Andric
397480093f4SDimitry Andric } // anonymous namespace
3980b57cec5SDimitry Andric
error(const Twine & Message)3990b57cec5SDimitry Andric static Error error(const Twine &Message) {
4000b57cec5SDimitry Andric return make_error<StringError>(
4010b57cec5SDimitry Andric Message, make_error_code(BitcodeError::CorruptedBitcode));
4020b57cec5SDimitry Andric }
4030b57cec5SDimitry Andric
4040b57cec5SDimitry Andric class MetadataLoader::MetadataLoaderImpl {
4050b57cec5SDimitry Andric BitcodeReaderMetadataList MetadataList;
4060b57cec5SDimitry Andric BitcodeReaderValueList &ValueList;
4070b57cec5SDimitry Andric BitstreamCursor &Stream;
4080b57cec5SDimitry Andric LLVMContext &Context;
4090b57cec5SDimitry Andric Module &TheModule;
410bdd1243dSDimitry Andric MetadataLoaderCallbacks Callbacks;
4110b57cec5SDimitry Andric
4120b57cec5SDimitry Andric /// Cursor associated with the lazy-loading of Metadata. This is the easy way
4130b57cec5SDimitry Andric /// to keep around the right "context" (Abbrev list) to be able to jump in
4140b57cec5SDimitry Andric /// the middle of the metadata block and load any record.
4150b57cec5SDimitry Andric BitstreamCursor IndexCursor;
4160b57cec5SDimitry Andric
4170b57cec5SDimitry Andric /// Index that keeps track of MDString values.
4180b57cec5SDimitry Andric std::vector<StringRef> MDStringRef;
4190b57cec5SDimitry Andric
4200b57cec5SDimitry Andric /// On-demand loading of a single MDString. Requires the index above to be
4210b57cec5SDimitry Andric /// populated.
4220b57cec5SDimitry Andric MDString *lazyLoadOneMDString(unsigned Idx);
4230b57cec5SDimitry Andric
4240b57cec5SDimitry Andric /// Index that keeps track of where to find a metadata record in the stream.
4250b57cec5SDimitry Andric std::vector<uint64_t> GlobalMetadataBitPosIndex;
4260b57cec5SDimitry Andric
427e8d8bef9SDimitry Andric /// Cursor position of the start of the global decl attachments, to enable
428e8d8bef9SDimitry Andric /// loading using the index built for lazy loading, instead of forward
429e8d8bef9SDimitry Andric /// references.
430e8d8bef9SDimitry Andric uint64_t GlobalDeclAttachmentPos = 0;
431e8d8bef9SDimitry Andric
432e8d8bef9SDimitry Andric #ifndef NDEBUG
4334824e7fdSDimitry Andric /// Baisic correctness check that we end up parsing all of the global decl
4344824e7fdSDimitry Andric /// attachments.
435e8d8bef9SDimitry Andric unsigned NumGlobalDeclAttachSkipped = 0;
436e8d8bef9SDimitry Andric unsigned NumGlobalDeclAttachParsed = 0;
437e8d8bef9SDimitry Andric #endif
438e8d8bef9SDimitry Andric
439e8d8bef9SDimitry Andric /// Load the global decl attachments, using the index built for lazy loading.
440e8d8bef9SDimitry Andric Expected<bool> loadGlobalDeclAttachments();
441e8d8bef9SDimitry Andric
4420b57cec5SDimitry Andric /// Populate the index above to enable lazily loading of metadata, and load
4430b57cec5SDimitry Andric /// the named metadata as well as the transitively referenced global
4440b57cec5SDimitry Andric /// Metadata.
4450b57cec5SDimitry Andric Expected<bool> lazyLoadModuleMetadataBlock();
4460b57cec5SDimitry Andric
4470b57cec5SDimitry Andric /// On-demand loading of a single metadata. Requires the index above to be
4480b57cec5SDimitry Andric /// populated.
4490b57cec5SDimitry Andric void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
4500b57cec5SDimitry Andric
4510b57cec5SDimitry Andric // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
4520b57cec5SDimitry Andric // point from SP to CU after a block is completly parsed.
4530b57cec5SDimitry Andric std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
4540b57cec5SDimitry Andric
4550b57cec5SDimitry Andric /// Functions that need to be matched with subprograms when upgrading old
4560b57cec5SDimitry Andric /// metadata.
4570b57cec5SDimitry Andric SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
4580b57cec5SDimitry Andric
4590b57cec5SDimitry Andric // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
4600b57cec5SDimitry Andric DenseMap<unsigned, unsigned> MDKindMap;
4610b57cec5SDimitry Andric
4620b57cec5SDimitry Andric bool StripTBAA = false;
4630b57cec5SDimitry Andric bool HasSeenOldLoopTags = false;
4640b57cec5SDimitry Andric bool NeedUpgradeToDIGlobalVariableExpression = false;
4650b57cec5SDimitry Andric bool NeedDeclareExpressionUpgrade = false;
4660b57cec5SDimitry Andric
467fe013be4SDimitry Andric /// Map DILocalScope to the enclosing DISubprogram, if any.
468fe013be4SDimitry Andric DenseMap<DILocalScope *, DISubprogram *> ParentSubprogram;
469fe013be4SDimitry Andric
4700b57cec5SDimitry Andric /// True if metadata is being parsed for a module being ThinLTO imported.
4710b57cec5SDimitry Andric bool IsImporting = false;
4720b57cec5SDimitry Andric
4730b57cec5SDimitry Andric Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
4740b57cec5SDimitry Andric PlaceholderQueue &Placeholders, StringRef Blob,
4750b57cec5SDimitry Andric unsigned &NextMetadataNo);
4760b57cec5SDimitry Andric Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
4770b57cec5SDimitry Andric function_ref<void(StringRef)> CallBack);
4780b57cec5SDimitry Andric Error parseGlobalObjectAttachment(GlobalObject &GO,
4790b57cec5SDimitry Andric ArrayRef<uint64_t> Record);
4800b57cec5SDimitry Andric Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
4810b57cec5SDimitry Andric
4820b57cec5SDimitry Andric void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
4830b57cec5SDimitry Andric
4840b57cec5SDimitry Andric /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
upgradeCUSubprograms()4850b57cec5SDimitry Andric void upgradeCUSubprograms() {
4860b57cec5SDimitry Andric for (auto CU_SP : CUSubprograms)
4870b57cec5SDimitry Andric if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
4880b57cec5SDimitry Andric for (auto &Op : SPs->operands())
4890b57cec5SDimitry Andric if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
4900b57cec5SDimitry Andric SP->replaceUnit(CU_SP.first);
4910b57cec5SDimitry Andric CUSubprograms.clear();
4920b57cec5SDimitry Andric }
4930b57cec5SDimitry Andric
4940b57cec5SDimitry Andric /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
upgradeCUVariables()4950b57cec5SDimitry Andric void upgradeCUVariables() {
4960b57cec5SDimitry Andric if (!NeedUpgradeToDIGlobalVariableExpression)
4970b57cec5SDimitry Andric return;
4980b57cec5SDimitry Andric
4990b57cec5SDimitry Andric // Upgrade list of variables attached to the CUs.
5000b57cec5SDimitry Andric if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
5010b57cec5SDimitry Andric for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
5020b57cec5SDimitry Andric auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
5030b57cec5SDimitry Andric if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
5040b57cec5SDimitry Andric for (unsigned I = 0; I < GVs->getNumOperands(); I++)
5050b57cec5SDimitry Andric if (auto *GV =
5060b57cec5SDimitry Andric dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
5070b57cec5SDimitry Andric auto *DGVE = DIGlobalVariableExpression::getDistinct(
5080b57cec5SDimitry Andric Context, GV, DIExpression::get(Context, {}));
5090b57cec5SDimitry Andric GVs->replaceOperandWith(I, DGVE);
5100b57cec5SDimitry Andric }
5110b57cec5SDimitry Andric }
5120b57cec5SDimitry Andric
5130b57cec5SDimitry Andric // Upgrade variables attached to globals.
5140b57cec5SDimitry Andric for (auto &GV : TheModule.globals()) {
5150b57cec5SDimitry Andric SmallVector<MDNode *, 1> MDs;
5160b57cec5SDimitry Andric GV.getMetadata(LLVMContext::MD_dbg, MDs);
5170b57cec5SDimitry Andric GV.eraseMetadata(LLVMContext::MD_dbg);
5180b57cec5SDimitry Andric for (auto *MD : MDs)
5198bcb0991SDimitry Andric if (auto *DGV = dyn_cast<DIGlobalVariable>(MD)) {
5200b57cec5SDimitry Andric auto *DGVE = DIGlobalVariableExpression::getDistinct(
5210b57cec5SDimitry Andric Context, DGV, DIExpression::get(Context, {}));
5220b57cec5SDimitry Andric GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
5230b57cec5SDimitry Andric } else
5240b57cec5SDimitry Andric GV.addMetadata(LLVMContext::MD_dbg, *MD);
5250b57cec5SDimitry Andric }
5260b57cec5SDimitry Andric }
5270b57cec5SDimitry Andric
findEnclosingSubprogram(DILocalScope * S)528fe013be4SDimitry Andric DISubprogram *findEnclosingSubprogram(DILocalScope *S) {
529fe013be4SDimitry Andric if (!S)
530fe013be4SDimitry Andric return nullptr;
531fe013be4SDimitry Andric if (auto *SP = ParentSubprogram[S]) {
532fe013be4SDimitry Andric return SP;
533fe013be4SDimitry Andric }
534fe013be4SDimitry Andric
535fe013be4SDimitry Andric DILocalScope *InitialScope = S;
536fe013be4SDimitry Andric DenseSet<DILocalScope *> Visited;
537fe013be4SDimitry Andric while (S && !isa<DISubprogram>(S)) {
538fe013be4SDimitry Andric S = dyn_cast_or_null<DILocalScope>(S->getScope());
539fe013be4SDimitry Andric if (Visited.contains(S))
540fe013be4SDimitry Andric break;
541fe013be4SDimitry Andric Visited.insert(S);
542fe013be4SDimitry Andric }
543fe013be4SDimitry Andric ParentSubprogram[InitialScope] = llvm::dyn_cast_or_null<DISubprogram>(S);
544fe013be4SDimitry Andric
545fe013be4SDimitry Andric return ParentSubprogram[InitialScope];
546fe013be4SDimitry Andric }
547fe013be4SDimitry Andric
548fe013be4SDimitry Andric /// Move local imports from DICompileUnit's 'imports' field to
549fe013be4SDimitry Andric /// DISubprogram's retainedNodes.
upgradeCULocals()550fe013be4SDimitry Andric void upgradeCULocals() {
551fe013be4SDimitry Andric if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu")) {
552fe013be4SDimitry Andric for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
553fe013be4SDimitry Andric auto *CU = dyn_cast<DICompileUnit>(CUNodes->getOperand(I));
554fe013be4SDimitry Andric if (!CU)
555fe013be4SDimitry Andric continue;
556fe013be4SDimitry Andric
557c9157d92SDimitry Andric if (CU->getRawImportedEntities()) {
558fe013be4SDimitry Andric // Collect a set of imported entities to be moved.
559fe013be4SDimitry Andric SetVector<Metadata *> EntitiesToRemove;
560fe013be4SDimitry Andric for (Metadata *Op : CU->getImportedEntities()->operands()) {
561fe013be4SDimitry Andric auto *IE = cast<DIImportedEntity>(Op);
562c9157d92SDimitry Andric if (dyn_cast_or_null<DILocalScope>(IE->getScope())) {
563fe013be4SDimitry Andric EntitiesToRemove.insert(IE);
564fe013be4SDimitry Andric }
565fe013be4SDimitry Andric }
566fe013be4SDimitry Andric
567fe013be4SDimitry Andric if (!EntitiesToRemove.empty()) {
568fe013be4SDimitry Andric // Make a new list of CU's 'imports'.
569fe013be4SDimitry Andric SmallVector<Metadata *> NewImports;
570fe013be4SDimitry Andric for (Metadata *Op : CU->getImportedEntities()->operands()) {
571fe013be4SDimitry Andric if (!EntitiesToRemove.contains(cast<DIImportedEntity>(Op))) {
572fe013be4SDimitry Andric NewImports.push_back(Op);
573fe013be4SDimitry Andric }
574fe013be4SDimitry Andric }
575fe013be4SDimitry Andric
576fe013be4SDimitry Andric // Find DISubprogram corresponding to each entity.
577fe013be4SDimitry Andric std::map<DISubprogram *, SmallVector<Metadata *>> SPToEntities;
578fe013be4SDimitry Andric for (auto *I : EntitiesToRemove) {
579fe013be4SDimitry Andric auto *Entity = cast<DIImportedEntity>(I);
580fe013be4SDimitry Andric if (auto *SP = findEnclosingSubprogram(
581fe013be4SDimitry Andric cast<DILocalScope>(Entity->getScope()))) {
582fe013be4SDimitry Andric SPToEntities[SP].push_back(Entity);
583fe013be4SDimitry Andric }
584fe013be4SDimitry Andric }
585fe013be4SDimitry Andric
586fe013be4SDimitry Andric // Update DISubprograms' retainedNodes.
587fe013be4SDimitry Andric for (auto I = SPToEntities.begin(); I != SPToEntities.end(); ++I) {
588fe013be4SDimitry Andric auto *SP = I->first;
589fe013be4SDimitry Andric auto RetainedNodes = SP->getRetainedNodes();
590fe013be4SDimitry Andric SmallVector<Metadata *> MDs(RetainedNodes.begin(),
591fe013be4SDimitry Andric RetainedNodes.end());
592fe013be4SDimitry Andric MDs.append(I->second);
593fe013be4SDimitry Andric SP->replaceRetainedNodes(MDNode::get(Context, MDs));
594fe013be4SDimitry Andric }
595fe013be4SDimitry Andric
596fe013be4SDimitry Andric // Remove entities with local scope from CU.
597fe013be4SDimitry Andric CU->replaceImportedEntities(MDTuple::get(Context, NewImports));
598fe013be4SDimitry Andric }
599fe013be4SDimitry Andric }
600fe013be4SDimitry Andric }
601fe013be4SDimitry Andric }
602fe013be4SDimitry Andric
603fe013be4SDimitry Andric ParentSubprogram.clear();
604fe013be4SDimitry Andric }
605fe013be4SDimitry Andric
6060b57cec5SDimitry Andric /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
6070b57cec5SDimitry Andric /// describes a function argument.
upgradeDeclareExpressions(Function & F)6080b57cec5SDimitry Andric void upgradeDeclareExpressions(Function &F) {
6090b57cec5SDimitry Andric if (!NeedDeclareExpressionUpgrade)
6100b57cec5SDimitry Andric return;
6110b57cec5SDimitry Andric
6120b57cec5SDimitry Andric for (auto &BB : F)
6130b57cec5SDimitry Andric for (auto &I : BB)
6140b57cec5SDimitry Andric if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
6150b57cec5SDimitry Andric if (auto *DIExpr = DDI->getExpression())
6160b57cec5SDimitry Andric if (DIExpr->startsWithDeref() &&
617349cc55cSDimitry Andric isa_and_nonnull<Argument>(DDI->getAddress())) {
6180b57cec5SDimitry Andric SmallVector<uint64_t, 8> Ops;
6190b57cec5SDimitry Andric Ops.append(std::next(DIExpr->elements_begin()),
6200b57cec5SDimitry Andric DIExpr->elements_end());
621fe6060f1SDimitry Andric DDI->setExpression(DIExpression::get(Context, Ops));
6220b57cec5SDimitry Andric }
6230b57cec5SDimitry Andric }
6240b57cec5SDimitry Andric
6250b57cec5SDimitry Andric /// Upgrade the expression from previous versions.
upgradeDIExpression(uint64_t FromVersion,MutableArrayRef<uint64_t> & Expr,SmallVectorImpl<uint64_t> & Buffer)6260b57cec5SDimitry Andric Error upgradeDIExpression(uint64_t FromVersion,
6270b57cec5SDimitry Andric MutableArrayRef<uint64_t> &Expr,
6280b57cec5SDimitry Andric SmallVectorImpl<uint64_t> &Buffer) {
6290b57cec5SDimitry Andric auto N = Expr.size();
6300b57cec5SDimitry Andric switch (FromVersion) {
6310b57cec5SDimitry Andric default:
6320b57cec5SDimitry Andric return error("Invalid record");
6330b57cec5SDimitry Andric case 0:
6340b57cec5SDimitry Andric if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
6350b57cec5SDimitry Andric Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
636bdd1243dSDimitry Andric [[fallthrough]];
6370b57cec5SDimitry Andric case 1:
6380b57cec5SDimitry Andric // Move DW_OP_deref to the end.
6390b57cec5SDimitry Andric if (N && Expr[0] == dwarf::DW_OP_deref) {
6400b57cec5SDimitry Andric auto End = Expr.end();
6410b57cec5SDimitry Andric if (Expr.size() >= 3 &&
6420b57cec5SDimitry Andric *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment)
6430b57cec5SDimitry Andric End = std::prev(End, 3);
6440b57cec5SDimitry Andric std::move(std::next(Expr.begin()), End, Expr.begin());
6450b57cec5SDimitry Andric *std::prev(End) = dwarf::DW_OP_deref;
6460b57cec5SDimitry Andric }
6470b57cec5SDimitry Andric NeedDeclareExpressionUpgrade = true;
648bdd1243dSDimitry Andric [[fallthrough]];
6490b57cec5SDimitry Andric case 2: {
6500b57cec5SDimitry Andric // Change DW_OP_plus to DW_OP_plus_uconst.
6510b57cec5SDimitry Andric // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
6520b57cec5SDimitry Andric auto SubExpr = ArrayRef<uint64_t>(Expr);
6530b57cec5SDimitry Andric while (!SubExpr.empty()) {
6540b57cec5SDimitry Andric // Skip past other operators with their operands
6550b57cec5SDimitry Andric // for this version of the IR, obtained from
6560b57cec5SDimitry Andric // from historic DIExpression::ExprOperand::getSize().
6570b57cec5SDimitry Andric size_t HistoricSize;
6580b57cec5SDimitry Andric switch (SubExpr.front()) {
6590b57cec5SDimitry Andric default:
6600b57cec5SDimitry Andric HistoricSize = 1;
6610b57cec5SDimitry Andric break;
6620b57cec5SDimitry Andric case dwarf::DW_OP_constu:
6630b57cec5SDimitry Andric case dwarf::DW_OP_minus:
6640b57cec5SDimitry Andric case dwarf::DW_OP_plus:
6650b57cec5SDimitry Andric HistoricSize = 2;
6660b57cec5SDimitry Andric break;
6670b57cec5SDimitry Andric case dwarf::DW_OP_LLVM_fragment:
6680b57cec5SDimitry Andric HistoricSize = 3;
6690b57cec5SDimitry Andric break;
6700b57cec5SDimitry Andric }
6710b57cec5SDimitry Andric
6720b57cec5SDimitry Andric // If the expression is malformed, make sure we don't
6730b57cec5SDimitry Andric // copy more elements than we should.
6740b57cec5SDimitry Andric HistoricSize = std::min(SubExpr.size(), HistoricSize);
6750b57cec5SDimitry Andric ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize - 1);
6760b57cec5SDimitry Andric
6770b57cec5SDimitry Andric switch (SubExpr.front()) {
6780b57cec5SDimitry Andric case dwarf::DW_OP_plus:
6790b57cec5SDimitry Andric Buffer.push_back(dwarf::DW_OP_plus_uconst);
6800b57cec5SDimitry Andric Buffer.append(Args.begin(), Args.end());
6810b57cec5SDimitry Andric break;
6820b57cec5SDimitry Andric case dwarf::DW_OP_minus:
6830b57cec5SDimitry Andric Buffer.push_back(dwarf::DW_OP_constu);
6840b57cec5SDimitry Andric Buffer.append(Args.begin(), Args.end());
6850b57cec5SDimitry Andric Buffer.push_back(dwarf::DW_OP_minus);
6860b57cec5SDimitry Andric break;
6870b57cec5SDimitry Andric default:
6880b57cec5SDimitry Andric Buffer.push_back(*SubExpr.begin());
6890b57cec5SDimitry Andric Buffer.append(Args.begin(), Args.end());
6900b57cec5SDimitry Andric break;
6910b57cec5SDimitry Andric }
6920b57cec5SDimitry Andric
6930b57cec5SDimitry Andric // Continue with remaining elements.
6940b57cec5SDimitry Andric SubExpr = SubExpr.slice(HistoricSize);
6950b57cec5SDimitry Andric }
6960b57cec5SDimitry Andric Expr = MutableArrayRef<uint64_t>(Buffer);
697bdd1243dSDimitry Andric [[fallthrough]];
6980b57cec5SDimitry Andric }
6990b57cec5SDimitry Andric case 3:
7000b57cec5SDimitry Andric // Up-to-date!
7010b57cec5SDimitry Andric break;
7020b57cec5SDimitry Andric }
7030b57cec5SDimitry Andric
7040b57cec5SDimitry Andric return Error::success();
7050b57cec5SDimitry Andric }
7060b57cec5SDimitry Andric
upgradeDebugInfo(bool ModuleLevel)707c9157d92SDimitry Andric void upgradeDebugInfo(bool ModuleLevel) {
7080b57cec5SDimitry Andric upgradeCUSubprograms();
7090b57cec5SDimitry Andric upgradeCUVariables();
710c9157d92SDimitry Andric if (ModuleLevel)
711fe013be4SDimitry Andric upgradeCULocals();
7120b57cec5SDimitry Andric }
7130b57cec5SDimitry Andric
714bdd1243dSDimitry Andric void callMDTypeCallback(Metadata **Val, unsigned TypeID);
715bdd1243dSDimitry Andric
7160b57cec5SDimitry Andric public:
MetadataLoaderImpl(BitstreamCursor & Stream,Module & TheModule,BitcodeReaderValueList & ValueList,MetadataLoaderCallbacks Callbacks,bool IsImporting)7170b57cec5SDimitry Andric MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
7180b57cec5SDimitry Andric BitcodeReaderValueList &ValueList,
719bdd1243dSDimitry Andric MetadataLoaderCallbacks Callbacks, bool IsImporting)
7200b57cec5SDimitry Andric : MetadataList(TheModule.getContext(), Stream.SizeInBytes()),
7210b57cec5SDimitry Andric ValueList(ValueList), Stream(Stream), Context(TheModule.getContext()),
722bdd1243dSDimitry Andric TheModule(TheModule), Callbacks(std::move(Callbacks)),
7230b57cec5SDimitry Andric IsImporting(IsImporting) {}
7240b57cec5SDimitry Andric
7250b57cec5SDimitry Andric Error parseMetadata(bool ModuleLevel);
7260b57cec5SDimitry Andric
hasFwdRefs() const7270b57cec5SDimitry Andric bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
7280b57cec5SDimitry Andric
getMetadataFwdRefOrLoad(unsigned ID)7290b57cec5SDimitry Andric Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
7300b57cec5SDimitry Andric if (ID < MDStringRef.size())
7310b57cec5SDimitry Andric return lazyLoadOneMDString(ID);
7320b57cec5SDimitry Andric if (auto *MD = MetadataList.lookup(ID))
7330b57cec5SDimitry Andric return MD;
7340b57cec5SDimitry Andric // If lazy-loading is enabled, we try recursively to load the operand
7350b57cec5SDimitry Andric // instead of creating a temporary.
7360b57cec5SDimitry Andric if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
7370b57cec5SDimitry Andric PlaceholderQueue Placeholders;
7380b57cec5SDimitry Andric lazyLoadOneMetadata(ID, Placeholders);
7390b57cec5SDimitry Andric resolveForwardRefsAndPlaceholders(Placeholders);
7400b57cec5SDimitry Andric return MetadataList.lookup(ID);
7410b57cec5SDimitry Andric }
7420b57cec5SDimitry Andric return MetadataList.getMetadataFwdRef(ID);
7430b57cec5SDimitry Andric }
7440b57cec5SDimitry Andric
lookupSubprogramForFunction(Function * F)7450b57cec5SDimitry Andric DISubprogram *lookupSubprogramForFunction(Function *F) {
7460b57cec5SDimitry Andric return FunctionsWithSPs.lookup(F);
7470b57cec5SDimitry Andric }
7480b57cec5SDimitry Andric
hasSeenOldLoopTags() const749e8d8bef9SDimitry Andric bool hasSeenOldLoopTags() const { return HasSeenOldLoopTags; }
7500b57cec5SDimitry Andric
75181ad6265SDimitry Andric Error parseMetadataAttachment(Function &F,
75281ad6265SDimitry Andric ArrayRef<Instruction *> InstructionList);
7530b57cec5SDimitry Andric
7540b57cec5SDimitry Andric Error parseMetadataKinds();
7550b57cec5SDimitry Andric
setStripTBAA(bool Value)7560b57cec5SDimitry Andric void setStripTBAA(bool Value) { StripTBAA = Value; }
isStrippingTBAA() const757e8d8bef9SDimitry Andric bool isStrippingTBAA() const { return StripTBAA; }
7580b57cec5SDimitry Andric
size() const7590b57cec5SDimitry Andric unsigned size() const { return MetadataList.size(); }
shrinkTo(unsigned N)7600b57cec5SDimitry Andric void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
upgradeDebugIntrinsics(Function & F)7610b57cec5SDimitry Andric void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); }
7620b57cec5SDimitry Andric };
7630b57cec5SDimitry Andric
7640b57cec5SDimitry Andric Expected<bool>
lazyLoadModuleMetadataBlock()7650b57cec5SDimitry Andric MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
7660b57cec5SDimitry Andric IndexCursor = Stream;
7670b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record;
768e8d8bef9SDimitry Andric GlobalDeclAttachmentPos = 0;
7690b57cec5SDimitry Andric // Get the abbrevs, and preload record positions to make them lazy-loadable.
7700b57cec5SDimitry Andric while (true) {
771e8d8bef9SDimitry Andric uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
772349cc55cSDimitry Andric BitstreamEntry Entry;
773349cc55cSDimitry Andric if (Error E =
774349cc55cSDimitry Andric IndexCursor
775349cc55cSDimitry Andric .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
776349cc55cSDimitry Andric .moveInto(Entry))
777349cc55cSDimitry Andric return std::move(E);
7780b57cec5SDimitry Andric
7790b57cec5SDimitry Andric switch (Entry.Kind) {
7800b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
7810b57cec5SDimitry Andric case BitstreamEntry::Error:
7820b57cec5SDimitry Andric return error("Malformed block");
7830b57cec5SDimitry Andric case BitstreamEntry::EndBlock: {
7840b57cec5SDimitry Andric return true;
7850b57cec5SDimitry Andric }
7860b57cec5SDimitry Andric case BitstreamEntry::Record: {
7870b57cec5SDimitry Andric // The interesting case.
7880b57cec5SDimitry Andric ++NumMDRecordLoaded;
7890b57cec5SDimitry Andric uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
790349cc55cSDimitry Andric unsigned Code;
791349cc55cSDimitry Andric if (Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
792349cc55cSDimitry Andric return std::move(E);
7930b57cec5SDimitry Andric switch (Code) {
7940b57cec5SDimitry Andric case bitc::METADATA_STRINGS: {
7950b57cec5SDimitry Andric // Rewind and parse the strings.
7960b57cec5SDimitry Andric if (Error Err = IndexCursor.JumpToBit(CurrentPos))
7970b57cec5SDimitry Andric return std::move(Err);
7980b57cec5SDimitry Andric StringRef Blob;
7990b57cec5SDimitry Andric Record.clear();
8000b57cec5SDimitry Andric if (Expected<unsigned> MaybeRecord =
8010b57cec5SDimitry Andric IndexCursor.readRecord(Entry.ID, Record, &Blob))
8020b57cec5SDimitry Andric ;
8030b57cec5SDimitry Andric else
8040b57cec5SDimitry Andric return MaybeRecord.takeError();
8050b57cec5SDimitry Andric unsigned NumStrings = Record[0];
8060b57cec5SDimitry Andric MDStringRef.reserve(NumStrings);
8070b57cec5SDimitry Andric auto IndexNextMDString = [&](StringRef Str) {
8080b57cec5SDimitry Andric MDStringRef.push_back(Str);
8090b57cec5SDimitry Andric };
8100b57cec5SDimitry Andric if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
8110b57cec5SDimitry Andric return std::move(Err);
8120b57cec5SDimitry Andric break;
8130b57cec5SDimitry Andric }
8140b57cec5SDimitry Andric case bitc::METADATA_INDEX_OFFSET: {
8150b57cec5SDimitry Andric // This is the offset to the index, when we see this we skip all the
8160b57cec5SDimitry Andric // records and load only an index to these.
8170b57cec5SDimitry Andric if (Error Err = IndexCursor.JumpToBit(CurrentPos))
8180b57cec5SDimitry Andric return std::move(Err);
8190b57cec5SDimitry Andric Record.clear();
8200b57cec5SDimitry Andric if (Expected<unsigned> MaybeRecord =
8210b57cec5SDimitry Andric IndexCursor.readRecord(Entry.ID, Record))
8220b57cec5SDimitry Andric ;
8230b57cec5SDimitry Andric else
8240b57cec5SDimitry Andric return MaybeRecord.takeError();
8250b57cec5SDimitry Andric if (Record.size() != 2)
8260b57cec5SDimitry Andric return error("Invalid record");
8270b57cec5SDimitry Andric auto Offset = Record[0] + (Record[1] << 32);
8280b57cec5SDimitry Andric auto BeginPos = IndexCursor.GetCurrentBitNo();
8290b57cec5SDimitry Andric if (Error Err = IndexCursor.JumpToBit(BeginPos + Offset))
8300b57cec5SDimitry Andric return std::move(Err);
8310b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry =
8320b57cec5SDimitry Andric IndexCursor.advanceSkippingSubblocks(
8330b57cec5SDimitry Andric BitstreamCursor::AF_DontPopBlockAtEnd);
8340b57cec5SDimitry Andric if (!MaybeEntry)
8350b57cec5SDimitry Andric return MaybeEntry.takeError();
8360b57cec5SDimitry Andric Entry = MaybeEntry.get();
8370b57cec5SDimitry Andric assert(Entry.Kind == BitstreamEntry::Record &&
8380b57cec5SDimitry Andric "Corrupted bitcode: Expected `Record` when trying to find the "
8390b57cec5SDimitry Andric "Metadata index");
8400b57cec5SDimitry Andric Record.clear();
8410b57cec5SDimitry Andric if (Expected<unsigned> MaybeCode =
8420b57cec5SDimitry Andric IndexCursor.readRecord(Entry.ID, Record))
8430b57cec5SDimitry Andric assert(MaybeCode.get() == bitc::METADATA_INDEX &&
8440b57cec5SDimitry Andric "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
8450b57cec5SDimitry Andric "find the Metadata index");
8460b57cec5SDimitry Andric else
8470b57cec5SDimitry Andric return MaybeCode.takeError();
8480b57cec5SDimitry Andric // Delta unpack
8490b57cec5SDimitry Andric auto CurrentValue = BeginPos;
8500b57cec5SDimitry Andric GlobalMetadataBitPosIndex.reserve(Record.size());
8510b57cec5SDimitry Andric for (auto &Elt : Record) {
8520b57cec5SDimitry Andric CurrentValue += Elt;
8530b57cec5SDimitry Andric GlobalMetadataBitPosIndex.push_back(CurrentValue);
8540b57cec5SDimitry Andric }
8550b57cec5SDimitry Andric break;
8560b57cec5SDimitry Andric }
8570b57cec5SDimitry Andric case bitc::METADATA_INDEX:
8580b57cec5SDimitry Andric // We don't expect to get there, the Index is loaded when we encounter
8590b57cec5SDimitry Andric // the offset.
8600b57cec5SDimitry Andric return error("Corrupted Metadata block");
8610b57cec5SDimitry Andric case bitc::METADATA_NAME: {
8620b57cec5SDimitry Andric // Named metadata need to be materialized now and aren't deferred.
8630b57cec5SDimitry Andric if (Error Err = IndexCursor.JumpToBit(CurrentPos))
8640b57cec5SDimitry Andric return std::move(Err);
8650b57cec5SDimitry Andric Record.clear();
8660b57cec5SDimitry Andric
8670b57cec5SDimitry Andric unsigned Code;
8680b57cec5SDimitry Andric if (Expected<unsigned> MaybeCode =
8690b57cec5SDimitry Andric IndexCursor.readRecord(Entry.ID, Record)) {
8700b57cec5SDimitry Andric Code = MaybeCode.get();
8710b57cec5SDimitry Andric assert(Code == bitc::METADATA_NAME);
8720b57cec5SDimitry Andric } else
8730b57cec5SDimitry Andric return MaybeCode.takeError();
8740b57cec5SDimitry Andric
8750b57cec5SDimitry Andric // Read name of the named metadata.
8760b57cec5SDimitry Andric SmallString<8> Name(Record.begin(), Record.end());
8770b57cec5SDimitry Andric if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
8780b57cec5SDimitry Andric Code = MaybeCode.get();
8790b57cec5SDimitry Andric else
8800b57cec5SDimitry Andric return MaybeCode.takeError();
8810b57cec5SDimitry Andric
8820b57cec5SDimitry Andric // Named Metadata comes in two parts, we expect the name to be followed
8830b57cec5SDimitry Andric // by the node
8840b57cec5SDimitry Andric Record.clear();
8850b57cec5SDimitry Andric if (Expected<unsigned> MaybeNextBitCode =
8860b57cec5SDimitry Andric IndexCursor.readRecord(Code, Record))
8870b57cec5SDimitry Andric assert(MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE);
8880b57cec5SDimitry Andric else
8890b57cec5SDimitry Andric return MaybeNextBitCode.takeError();
8900b57cec5SDimitry Andric
8910b57cec5SDimitry Andric // Read named metadata elements.
8920b57cec5SDimitry Andric unsigned Size = Record.size();
8930b57cec5SDimitry Andric NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
8940b57cec5SDimitry Andric for (unsigned i = 0; i != Size; ++i) {
8950b57cec5SDimitry Andric // FIXME: We could use a placeholder here, however NamedMDNode are
8960b57cec5SDimitry Andric // taking MDNode as operand and not using the Metadata infrastructure.
8970b57cec5SDimitry Andric // It is acknowledged by 'TODO: Inherit from Metadata' in the
8980b57cec5SDimitry Andric // NamedMDNode class definition.
8990b57cec5SDimitry Andric MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
9000b57cec5SDimitry Andric assert(MD && "Invalid metadata: expect fwd ref to MDNode");
9010b57cec5SDimitry Andric NMD->addOperand(MD);
9020b57cec5SDimitry Andric }
9030b57cec5SDimitry Andric break;
9040b57cec5SDimitry Andric }
9050b57cec5SDimitry Andric case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
906e8d8bef9SDimitry Andric if (!GlobalDeclAttachmentPos)
907e8d8bef9SDimitry Andric GlobalDeclAttachmentPos = SavedPos;
908e8d8bef9SDimitry Andric #ifndef NDEBUG
909e8d8bef9SDimitry Andric NumGlobalDeclAttachSkipped++;
910e8d8bef9SDimitry Andric #endif
9110b57cec5SDimitry Andric break;
9120b57cec5SDimitry Andric }
9130b57cec5SDimitry Andric case bitc::METADATA_KIND:
9140b57cec5SDimitry Andric case bitc::METADATA_STRING_OLD:
9150b57cec5SDimitry Andric case bitc::METADATA_OLD_FN_NODE:
9160b57cec5SDimitry Andric case bitc::METADATA_OLD_NODE:
9170b57cec5SDimitry Andric case bitc::METADATA_VALUE:
9180b57cec5SDimitry Andric case bitc::METADATA_DISTINCT_NODE:
9190b57cec5SDimitry Andric case bitc::METADATA_NODE:
9200b57cec5SDimitry Andric case bitc::METADATA_LOCATION:
9210b57cec5SDimitry Andric case bitc::METADATA_GENERIC_DEBUG:
9220b57cec5SDimitry Andric case bitc::METADATA_SUBRANGE:
9230b57cec5SDimitry Andric case bitc::METADATA_ENUMERATOR:
9240b57cec5SDimitry Andric case bitc::METADATA_BASIC_TYPE:
925e8d8bef9SDimitry Andric case bitc::METADATA_STRING_TYPE:
9260b57cec5SDimitry Andric case bitc::METADATA_DERIVED_TYPE:
9270b57cec5SDimitry Andric case bitc::METADATA_COMPOSITE_TYPE:
9280b57cec5SDimitry Andric case bitc::METADATA_SUBROUTINE_TYPE:
9290b57cec5SDimitry Andric case bitc::METADATA_MODULE:
9300b57cec5SDimitry Andric case bitc::METADATA_FILE:
9310b57cec5SDimitry Andric case bitc::METADATA_COMPILE_UNIT:
9320b57cec5SDimitry Andric case bitc::METADATA_SUBPROGRAM:
9330b57cec5SDimitry Andric case bitc::METADATA_LEXICAL_BLOCK:
9340b57cec5SDimitry Andric case bitc::METADATA_LEXICAL_BLOCK_FILE:
9350b57cec5SDimitry Andric case bitc::METADATA_NAMESPACE:
9360b57cec5SDimitry Andric case bitc::METADATA_COMMON_BLOCK:
9370b57cec5SDimitry Andric case bitc::METADATA_MACRO:
9380b57cec5SDimitry Andric case bitc::METADATA_MACRO_FILE:
9390b57cec5SDimitry Andric case bitc::METADATA_TEMPLATE_TYPE:
9400b57cec5SDimitry Andric case bitc::METADATA_TEMPLATE_VALUE:
9410b57cec5SDimitry Andric case bitc::METADATA_GLOBAL_VAR:
9420b57cec5SDimitry Andric case bitc::METADATA_LOCAL_VAR:
943bdd1243dSDimitry Andric case bitc::METADATA_ASSIGN_ID:
9440b57cec5SDimitry Andric case bitc::METADATA_LABEL:
9450b57cec5SDimitry Andric case bitc::METADATA_EXPRESSION:
9460b57cec5SDimitry Andric case bitc::METADATA_OBJC_PROPERTY:
9470b57cec5SDimitry Andric case bitc::METADATA_IMPORTED_ENTITY:
9480b57cec5SDimitry Andric case bitc::METADATA_GLOBAL_VAR_EXPR:
949e8d8bef9SDimitry Andric case bitc::METADATA_GENERIC_SUBRANGE:
9500b57cec5SDimitry Andric // We don't expect to see any of these, if we see one, give up on
9510b57cec5SDimitry Andric // lazy-loading and fallback.
9520b57cec5SDimitry Andric MDStringRef.clear();
9530b57cec5SDimitry Andric GlobalMetadataBitPosIndex.clear();
9540b57cec5SDimitry Andric return false;
9550b57cec5SDimitry Andric }
9560b57cec5SDimitry Andric break;
9570b57cec5SDimitry Andric }
9580b57cec5SDimitry Andric }
9590b57cec5SDimitry Andric }
9600b57cec5SDimitry Andric }
9610b57cec5SDimitry Andric
962e8d8bef9SDimitry Andric // Load the global decl attachments after building the lazy loading index.
963e8d8bef9SDimitry Andric // We don't load them "lazily" - all global decl attachments must be
964e8d8bef9SDimitry Andric // parsed since they aren't materialized on demand. However, by delaying
965e8d8bef9SDimitry Andric // their parsing until after the index is created, we can use the index
966e8d8bef9SDimitry Andric // instead of creating temporaries.
loadGlobalDeclAttachments()967e8d8bef9SDimitry Andric Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
968e8d8bef9SDimitry Andric // Nothing to do if we didn't find any of these metadata records.
969e8d8bef9SDimitry Andric if (!GlobalDeclAttachmentPos)
970e8d8bef9SDimitry Andric return true;
971e8d8bef9SDimitry Andric // Use a temporary cursor so that we don't mess up the main Stream cursor or
972e8d8bef9SDimitry Andric // the lazy loading IndexCursor (which holds the necessary abbrev ids).
973e8d8bef9SDimitry Andric BitstreamCursor TempCursor = Stream;
974e8d8bef9SDimitry Andric SmallVector<uint64_t, 64> Record;
975e8d8bef9SDimitry Andric // Jump to the position before the first global decl attachment, so we can
976e8d8bef9SDimitry Andric // scan for the first BitstreamEntry record.
977e8d8bef9SDimitry Andric if (Error Err = TempCursor.JumpToBit(GlobalDeclAttachmentPos))
978e8d8bef9SDimitry Andric return std::move(Err);
979e8d8bef9SDimitry Andric while (true) {
980349cc55cSDimitry Andric BitstreamEntry Entry;
981349cc55cSDimitry Andric if (Error E =
982349cc55cSDimitry Andric TempCursor
983349cc55cSDimitry Andric .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
984349cc55cSDimitry Andric .moveInto(Entry))
985349cc55cSDimitry Andric return std::move(E);
986e8d8bef9SDimitry Andric
987e8d8bef9SDimitry Andric switch (Entry.Kind) {
988e8d8bef9SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
989e8d8bef9SDimitry Andric case BitstreamEntry::Error:
990e8d8bef9SDimitry Andric return error("Malformed block");
991e8d8bef9SDimitry Andric case BitstreamEntry::EndBlock:
9924824e7fdSDimitry Andric // Check that we parsed them all.
993e8d8bef9SDimitry Andric assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
994e8d8bef9SDimitry Andric return true;
995e8d8bef9SDimitry Andric case BitstreamEntry::Record:
996e8d8bef9SDimitry Andric break;
997e8d8bef9SDimitry Andric }
998e8d8bef9SDimitry Andric uint64_t CurrentPos = TempCursor.GetCurrentBitNo();
999e8d8bef9SDimitry Andric Expected<unsigned> MaybeCode = TempCursor.skipRecord(Entry.ID);
1000e8d8bef9SDimitry Andric if (!MaybeCode)
1001e8d8bef9SDimitry Andric return MaybeCode.takeError();
1002e8d8bef9SDimitry Andric if (MaybeCode.get() != bitc::METADATA_GLOBAL_DECL_ATTACHMENT) {
1003e8d8bef9SDimitry Andric // Anything other than a global decl attachment signals the end of
10044824e7fdSDimitry Andric // these records. Check that we parsed them all.
1005e8d8bef9SDimitry Andric assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1006e8d8bef9SDimitry Andric return true;
1007e8d8bef9SDimitry Andric }
1008e8d8bef9SDimitry Andric #ifndef NDEBUG
1009e8d8bef9SDimitry Andric NumGlobalDeclAttachParsed++;
1010e8d8bef9SDimitry Andric #endif
1011e8d8bef9SDimitry Andric // FIXME: we need to do this early because we don't materialize global
1012e8d8bef9SDimitry Andric // value explicitly.
1013e8d8bef9SDimitry Andric if (Error Err = TempCursor.JumpToBit(CurrentPos))
1014e8d8bef9SDimitry Andric return std::move(Err);
1015e8d8bef9SDimitry Andric Record.clear();
1016e8d8bef9SDimitry Andric if (Expected<unsigned> MaybeRecord =
1017e8d8bef9SDimitry Andric TempCursor.readRecord(Entry.ID, Record))
1018e8d8bef9SDimitry Andric ;
1019e8d8bef9SDimitry Andric else
1020e8d8bef9SDimitry Andric return MaybeRecord.takeError();
1021e8d8bef9SDimitry Andric if (Record.size() % 2 == 0)
1022e8d8bef9SDimitry Andric return error("Invalid record");
1023e8d8bef9SDimitry Andric unsigned ValueID = Record[0];
1024e8d8bef9SDimitry Andric if (ValueID >= ValueList.size())
1025e8d8bef9SDimitry Andric return error("Invalid record");
1026e8d8bef9SDimitry Andric if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) {
1027e8d8bef9SDimitry Andric // Need to save and restore the current position since
1028e8d8bef9SDimitry Andric // parseGlobalObjectAttachment will resolve all forward references which
1029e8d8bef9SDimitry Andric // would require parsing from locations stored in the index.
1030e8d8bef9SDimitry Andric CurrentPos = TempCursor.GetCurrentBitNo();
1031e8d8bef9SDimitry Andric if (Error Err = parseGlobalObjectAttachment(
1032e8d8bef9SDimitry Andric *GO, ArrayRef<uint64_t>(Record).slice(1)))
1033e8d8bef9SDimitry Andric return std::move(Err);
1034e8d8bef9SDimitry Andric if (Error Err = TempCursor.JumpToBit(CurrentPos))
1035e8d8bef9SDimitry Andric return std::move(Err);
1036e8d8bef9SDimitry Andric }
1037e8d8bef9SDimitry Andric }
1038e8d8bef9SDimitry Andric }
1039e8d8bef9SDimitry Andric
callMDTypeCallback(Metadata ** Val,unsigned TypeID)1040bdd1243dSDimitry Andric void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(Metadata **Val,
1041bdd1243dSDimitry Andric unsigned TypeID) {
1042bdd1243dSDimitry Andric if (Callbacks.MDType) {
1043bdd1243dSDimitry Andric (*Callbacks.MDType)(Val, TypeID, Callbacks.GetTypeByID,
1044bdd1243dSDimitry Andric Callbacks.GetContainedTypeID);
1045bdd1243dSDimitry Andric }
1046bdd1243dSDimitry Andric }
1047bdd1243dSDimitry Andric
10480b57cec5SDimitry Andric /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
10490b57cec5SDimitry Andric /// module level metadata.
parseMetadata(bool ModuleLevel)10500b57cec5SDimitry Andric Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
10510b57cec5SDimitry Andric if (!ModuleLevel && MetadataList.hasFwdRefs())
10520b57cec5SDimitry Andric return error("Invalid metadata: fwd refs into function blocks");
10530b57cec5SDimitry Andric
10540b57cec5SDimitry Andric // Record the entry position so that we can jump back here and efficiently
10550b57cec5SDimitry Andric // skip the whole block in case we lazy-load.
10560b57cec5SDimitry Andric auto EntryPos = Stream.GetCurrentBitNo();
10570b57cec5SDimitry Andric
10580b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
10590b57cec5SDimitry Andric return Err;
10600b57cec5SDimitry Andric
10610b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record;
10620b57cec5SDimitry Andric PlaceholderQueue Placeholders;
10630b57cec5SDimitry Andric
10640b57cec5SDimitry Andric // We lazy-load module-level metadata: we build an index for each record, and
10650b57cec5SDimitry Andric // then load individual record as needed, starting with the named metadata.
10660b57cec5SDimitry Andric if (ModuleLevel && IsImporting && MetadataList.empty() &&
10670b57cec5SDimitry Andric !DisableLazyLoading) {
10680b57cec5SDimitry Andric auto SuccessOrErr = lazyLoadModuleMetadataBlock();
10690b57cec5SDimitry Andric if (!SuccessOrErr)
10700b57cec5SDimitry Andric return SuccessOrErr.takeError();
10710b57cec5SDimitry Andric if (SuccessOrErr.get()) {
10720b57cec5SDimitry Andric // An index was successfully created and we will be able to load metadata
10730b57cec5SDimitry Andric // on-demand.
10740b57cec5SDimitry Andric MetadataList.resize(MDStringRef.size() +
10750b57cec5SDimitry Andric GlobalMetadataBitPosIndex.size());
10760b57cec5SDimitry Andric
1077e8d8bef9SDimitry Andric // Now that we have built the index, load the global decl attachments
1078e8d8bef9SDimitry Andric // that were deferred during that process. This avoids creating
1079e8d8bef9SDimitry Andric // temporaries.
1080e8d8bef9SDimitry Andric SuccessOrErr = loadGlobalDeclAttachments();
1081e8d8bef9SDimitry Andric if (!SuccessOrErr)
1082e8d8bef9SDimitry Andric return SuccessOrErr.takeError();
1083e8d8bef9SDimitry Andric assert(SuccessOrErr.get());
1084e8d8bef9SDimitry Andric
10850b57cec5SDimitry Andric // Reading the named metadata created forward references and/or
10860b57cec5SDimitry Andric // placeholders, that we flush here.
10870b57cec5SDimitry Andric resolveForwardRefsAndPlaceholders(Placeholders);
1088c9157d92SDimitry Andric upgradeDebugInfo(ModuleLevel);
10890b57cec5SDimitry Andric // Return at the beginning of the block, since it is easy to skip it
10900b57cec5SDimitry Andric // entirely from there.
10910b57cec5SDimitry Andric Stream.ReadBlockEnd(); // Pop the abbrev block context.
10920b57cec5SDimitry Andric if (Error Err = IndexCursor.JumpToBit(EntryPos))
10930b57cec5SDimitry Andric return Err;
10940b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) {
10950b57cec5SDimitry Andric // FIXME this drops the error on the floor, which
10960b57cec5SDimitry Andric // ThinLTO/X86/debuginfo-cu-import.ll relies on.
10970b57cec5SDimitry Andric consumeError(std::move(Err));
10980b57cec5SDimitry Andric return Error::success();
10990b57cec5SDimitry Andric }
11000b57cec5SDimitry Andric return Error::success();
11010b57cec5SDimitry Andric }
11020b57cec5SDimitry Andric // Couldn't load an index, fallback to loading all the block "old-style".
11030b57cec5SDimitry Andric }
11040b57cec5SDimitry Andric
11050b57cec5SDimitry Andric unsigned NextMetadataNo = MetadataList.size();
11060b57cec5SDimitry Andric
11070b57cec5SDimitry Andric // Read all the records.
11080b57cec5SDimitry Andric while (true) {
1109349cc55cSDimitry Andric BitstreamEntry Entry;
1110349cc55cSDimitry Andric if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1111349cc55cSDimitry Andric return E;
11120b57cec5SDimitry Andric
11130b57cec5SDimitry Andric switch (Entry.Kind) {
11140b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
11150b57cec5SDimitry Andric case BitstreamEntry::Error:
11160b57cec5SDimitry Andric return error("Malformed block");
11170b57cec5SDimitry Andric case BitstreamEntry::EndBlock:
11180b57cec5SDimitry Andric resolveForwardRefsAndPlaceholders(Placeholders);
1119c9157d92SDimitry Andric upgradeDebugInfo(ModuleLevel);
11200b57cec5SDimitry Andric return Error::success();
11210b57cec5SDimitry Andric case BitstreamEntry::Record:
11220b57cec5SDimitry Andric // The interesting case.
11230b57cec5SDimitry Andric break;
11240b57cec5SDimitry Andric }
11250b57cec5SDimitry Andric
11260b57cec5SDimitry Andric // Read a record.
11270b57cec5SDimitry Andric Record.clear();
11280b57cec5SDimitry Andric StringRef Blob;
11290b57cec5SDimitry Andric ++NumMDRecordLoaded;
11300b57cec5SDimitry Andric if (Expected<unsigned> MaybeCode =
11310b57cec5SDimitry Andric Stream.readRecord(Entry.ID, Record, &Blob)) {
11320b57cec5SDimitry Andric if (Error Err = parseOneMetadata(Record, MaybeCode.get(), Placeholders,
11330b57cec5SDimitry Andric Blob, NextMetadataNo))
11340b57cec5SDimitry Andric return Err;
11350b57cec5SDimitry Andric } else
11360b57cec5SDimitry Andric return MaybeCode.takeError();
11370b57cec5SDimitry Andric }
11380b57cec5SDimitry Andric }
11390b57cec5SDimitry Andric
lazyLoadOneMDString(unsigned ID)11400b57cec5SDimitry Andric MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
11410b57cec5SDimitry Andric ++NumMDStringLoaded;
11420b57cec5SDimitry Andric if (Metadata *MD = MetadataList.lookup(ID))
11430b57cec5SDimitry Andric return cast<MDString>(MD);
11440b57cec5SDimitry Andric auto MDS = MDString::get(Context, MDStringRef[ID]);
11450b57cec5SDimitry Andric MetadataList.assignValue(MDS, ID);
11460b57cec5SDimitry Andric return MDS;
11470b57cec5SDimitry Andric }
11480b57cec5SDimitry Andric
lazyLoadOneMetadata(unsigned ID,PlaceholderQueue & Placeholders)11490b57cec5SDimitry Andric void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
11500b57cec5SDimitry Andric unsigned ID, PlaceholderQueue &Placeholders) {
11510b57cec5SDimitry Andric assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
11520b57cec5SDimitry Andric assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
11530b57cec5SDimitry Andric // Lookup first if the metadata hasn't already been loaded.
11540b57cec5SDimitry Andric if (auto *MD = MetadataList.lookup(ID)) {
11558bcb0991SDimitry Andric auto *N = cast<MDNode>(MD);
11560b57cec5SDimitry Andric if (!N->isTemporary())
11570b57cec5SDimitry Andric return;
11580b57cec5SDimitry Andric }
11590b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record;
11600b57cec5SDimitry Andric StringRef Blob;
11610b57cec5SDimitry Andric if (Error Err = IndexCursor.JumpToBit(
11620b57cec5SDimitry Andric GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
11630b57cec5SDimitry Andric report_fatal_error("lazyLoadOneMetadata failed jumping: " +
1164349cc55cSDimitry Andric Twine(toString(std::move(Err))));
1165349cc55cSDimitry Andric BitstreamEntry Entry;
1166349cc55cSDimitry Andric if (Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
11670b57cec5SDimitry Andric // FIXME this drops the error on the floor.
11680b57cec5SDimitry Andric report_fatal_error("lazyLoadOneMetadata failed advanceSkippingSubblocks: " +
1169349cc55cSDimitry Andric Twine(toString(std::move(E))));
11700b57cec5SDimitry Andric ++NumMDRecordLoaded;
11710b57cec5SDimitry Andric if (Expected<unsigned> MaybeCode =
11720b57cec5SDimitry Andric IndexCursor.readRecord(Entry.ID, Record, &Blob)) {
11730b57cec5SDimitry Andric if (Error Err =
11740b57cec5SDimitry Andric parseOneMetadata(Record, MaybeCode.get(), Placeholders, Blob, ID))
11750b57cec5SDimitry Andric report_fatal_error("Can't lazyload MD, parseOneMetadata: " +
1176349cc55cSDimitry Andric Twine(toString(std::move(Err))));
11770b57cec5SDimitry Andric } else
1178349cc55cSDimitry Andric report_fatal_error("Can't lazyload MD: " +
1179349cc55cSDimitry Andric Twine(toString(MaybeCode.takeError())));
11800b57cec5SDimitry Andric }
11810b57cec5SDimitry Andric
11820b57cec5SDimitry Andric /// Ensure that all forward-references and placeholders are resolved.
11830b57cec5SDimitry Andric /// Iteratively lazy-loading metadata on-demand if needed.
resolveForwardRefsAndPlaceholders(PlaceholderQueue & Placeholders)11840b57cec5SDimitry Andric void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
11850b57cec5SDimitry Andric PlaceholderQueue &Placeholders) {
11860b57cec5SDimitry Andric DenseSet<unsigned> Temporaries;
118704eeddc0SDimitry Andric while (true) {
11880b57cec5SDimitry Andric // Populate Temporaries with the placeholders that haven't been loaded yet.
11890b57cec5SDimitry Andric Placeholders.getTemporaries(MetadataList, Temporaries);
11900b57cec5SDimitry Andric
11910b57cec5SDimitry Andric // If we don't have any temporary, or FwdReference, we're done!
11920b57cec5SDimitry Andric if (Temporaries.empty() && !MetadataList.hasFwdRefs())
11930b57cec5SDimitry Andric break;
11940b57cec5SDimitry Andric
11950b57cec5SDimitry Andric // First, load all the temporaries. This can add new placeholders or
11960b57cec5SDimitry Andric // forward references.
11970b57cec5SDimitry Andric for (auto ID : Temporaries)
11980b57cec5SDimitry Andric lazyLoadOneMetadata(ID, Placeholders);
11990b57cec5SDimitry Andric Temporaries.clear();
12000b57cec5SDimitry Andric
12010b57cec5SDimitry Andric // Second, load the forward-references. This can also add new placeholders
12020b57cec5SDimitry Andric // or forward references.
12030b57cec5SDimitry Andric while (MetadataList.hasFwdRefs())
12040b57cec5SDimitry Andric lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
12050b57cec5SDimitry Andric }
12060b57cec5SDimitry Andric // At this point we don't have any forward reference remaining, or temporary
12070b57cec5SDimitry Andric // that haven't been loaded. We can safely drop RAUW support and mark cycles
12080b57cec5SDimitry Andric // as resolved.
12090b57cec5SDimitry Andric MetadataList.tryToResolveCycles();
12100b57cec5SDimitry Andric
12110b57cec5SDimitry Andric // Finally, everything is in place, we can replace the placeholders operands
12120b57cec5SDimitry Andric // with the final node they refer to.
12130b57cec5SDimitry Andric Placeholders.flush(MetadataList);
12140b57cec5SDimitry Andric }
12150b57cec5SDimitry Andric
getValueFwdRef(BitcodeReaderValueList & ValueList,unsigned Idx,Type * Ty,unsigned TyID)1216c9157d92SDimitry Andric static Value *getValueFwdRef(BitcodeReaderValueList &ValueList, unsigned Idx,
1217c9157d92SDimitry Andric Type *Ty, unsigned TyID) {
1218c9157d92SDimitry Andric Value *V = ValueList.getValueFwdRef(Idx, Ty, TyID,
1219c9157d92SDimitry Andric /*ConstExprInsertBB*/ nullptr);
1220c9157d92SDimitry Andric if (V)
1221c9157d92SDimitry Andric return V;
1222c9157d92SDimitry Andric
1223c9157d92SDimitry Andric // This is a reference to a no longer supported constant expression.
1224c9157d92SDimitry Andric // Pretend that the constant was deleted, which will replace metadata
1225c9157d92SDimitry Andric // references with undef.
1226c9157d92SDimitry Andric // TODO: This is a rather indirect check. It would be more elegant to use
1227c9157d92SDimitry Andric // a separate ErrorInfo for constant materialization failure and thread
1228c9157d92SDimitry Andric // the error reporting through getValueFwdRef().
1229c9157d92SDimitry Andric if (Idx < ValueList.size() && ValueList[Idx] &&
1230c9157d92SDimitry Andric ValueList[Idx]->getType() == Ty)
1231c9157d92SDimitry Andric return UndefValue::get(Ty);
1232c9157d92SDimitry Andric
1233c9157d92SDimitry Andric return nullptr;
1234c9157d92SDimitry Andric }
1235c9157d92SDimitry Andric
parseOneMetadata(SmallVectorImpl<uint64_t> & Record,unsigned Code,PlaceholderQueue & Placeholders,StringRef Blob,unsigned & NextMetadataNo)12360b57cec5SDimitry Andric Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
12370b57cec5SDimitry Andric SmallVectorImpl<uint64_t> &Record, unsigned Code,
12380b57cec5SDimitry Andric PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
12390b57cec5SDimitry Andric
12400b57cec5SDimitry Andric bool IsDistinct = false;
12410b57cec5SDimitry Andric auto getMD = [&](unsigned ID) -> Metadata * {
12420b57cec5SDimitry Andric if (ID < MDStringRef.size())
12430b57cec5SDimitry Andric return lazyLoadOneMDString(ID);
12440b57cec5SDimitry Andric if (!IsDistinct) {
12450b57cec5SDimitry Andric if (auto *MD = MetadataList.lookup(ID))
12460b57cec5SDimitry Andric return MD;
12470b57cec5SDimitry Andric // If lazy-loading is enabled, we try recursively to load the operand
12480b57cec5SDimitry Andric // instead of creating a temporary.
12490b57cec5SDimitry Andric if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
12500b57cec5SDimitry Andric // Create a temporary for the node that is referencing the operand we
12510b57cec5SDimitry Andric // will lazy-load. It is needed before recursing in case there are
12520b57cec5SDimitry Andric // uniquing cycles.
12530b57cec5SDimitry Andric MetadataList.getMetadataFwdRef(NextMetadataNo);
12540b57cec5SDimitry Andric lazyLoadOneMetadata(ID, Placeholders);
12550b57cec5SDimitry Andric return MetadataList.lookup(ID);
12560b57cec5SDimitry Andric }
12570b57cec5SDimitry Andric // Return a temporary.
12580b57cec5SDimitry Andric return MetadataList.getMetadataFwdRef(ID);
12590b57cec5SDimitry Andric }
12600b57cec5SDimitry Andric if (auto *MD = MetadataList.getMetadataIfResolved(ID))
12610b57cec5SDimitry Andric return MD;
12620b57cec5SDimitry Andric return &Placeholders.getPlaceholderOp(ID);
12630b57cec5SDimitry Andric };
12640b57cec5SDimitry Andric auto getMDOrNull = [&](unsigned ID) -> Metadata * {
12650b57cec5SDimitry Andric if (ID)
12660b57cec5SDimitry Andric return getMD(ID - 1);
12670b57cec5SDimitry Andric return nullptr;
12680b57cec5SDimitry Andric };
12690b57cec5SDimitry Andric auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
12700b57cec5SDimitry Andric if (ID)
12710b57cec5SDimitry Andric return MetadataList.getMetadataFwdRef(ID - 1);
12720b57cec5SDimitry Andric return nullptr;
12730b57cec5SDimitry Andric };
12740b57cec5SDimitry Andric auto getMDString = [&](unsigned ID) -> MDString * {
12750b57cec5SDimitry Andric // This requires that the ID is not really a forward reference. In
12760b57cec5SDimitry Andric // particular, the MDString must already have been resolved.
12770b57cec5SDimitry Andric auto MDS = getMDOrNull(ID);
12780b57cec5SDimitry Andric return cast_or_null<MDString>(MDS);
12790b57cec5SDimitry Andric };
12800b57cec5SDimitry Andric
12810b57cec5SDimitry Andric // Support for old type refs.
12820b57cec5SDimitry Andric auto getDITypeRefOrNull = [&](unsigned ID) {
12830b57cec5SDimitry Andric return MetadataList.upgradeTypeRef(getMDOrNull(ID));
12840b57cec5SDimitry Andric };
12850b57cec5SDimitry Andric
12860b57cec5SDimitry Andric #define GET_OR_DISTINCT(CLASS, ARGS) \
12870b57cec5SDimitry Andric (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
12880b57cec5SDimitry Andric
12890b57cec5SDimitry Andric switch (Code) {
12900b57cec5SDimitry Andric default: // Default behavior: ignore.
12910b57cec5SDimitry Andric break;
12920b57cec5SDimitry Andric case bitc::METADATA_NAME: {
12930b57cec5SDimitry Andric // Read name of the named metadata.
12940b57cec5SDimitry Andric SmallString<8> Name(Record.begin(), Record.end());
12950b57cec5SDimitry Andric Record.clear();
1296349cc55cSDimitry Andric if (Error E = Stream.ReadCode().moveInto(Code))
1297349cc55cSDimitry Andric return E;
12980b57cec5SDimitry Andric
12990b57cec5SDimitry Andric ++NumMDRecordLoaded;
13000b57cec5SDimitry Andric if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
13010b57cec5SDimitry Andric if (MaybeNextBitCode.get() != bitc::METADATA_NAMED_NODE)
13020b57cec5SDimitry Andric return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
13030b57cec5SDimitry Andric } else
13040b57cec5SDimitry Andric return MaybeNextBitCode.takeError();
13050b57cec5SDimitry Andric
13060b57cec5SDimitry Andric // Read named metadata elements.
13070b57cec5SDimitry Andric unsigned Size = Record.size();
13080b57cec5SDimitry Andric NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
13090b57cec5SDimitry Andric for (unsigned i = 0; i != Size; ++i) {
13100b57cec5SDimitry Andric MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
13110b57cec5SDimitry Andric if (!MD)
13120b57cec5SDimitry Andric return error("Invalid named metadata: expect fwd ref to MDNode");
13130b57cec5SDimitry Andric NMD->addOperand(MD);
13140b57cec5SDimitry Andric }
13150b57cec5SDimitry Andric break;
13160b57cec5SDimitry Andric }
13170b57cec5SDimitry Andric case bitc::METADATA_OLD_FN_NODE: {
13185ffd83dbSDimitry Andric // Deprecated, but still needed to read old bitcode files.
13190b57cec5SDimitry Andric // This is a LocalAsMetadata record, the only type of function-local
13200b57cec5SDimitry Andric // metadata.
13210b57cec5SDimitry Andric if (Record.size() % 2 == 1)
13220b57cec5SDimitry Andric return error("Invalid record");
13230b57cec5SDimitry Andric
13240b57cec5SDimitry Andric // If this isn't a LocalAsMetadata record, we're dropping it. This used
13250b57cec5SDimitry Andric // to be legal, but there's no upgrade path.
13260b57cec5SDimitry Andric auto dropRecord = [&] {
1327bdd1243dSDimitry Andric MetadataList.assignValue(MDNode::get(Context, std::nullopt),
1328bdd1243dSDimitry Andric NextMetadataNo);
13290b57cec5SDimitry Andric NextMetadataNo++;
13300b57cec5SDimitry Andric };
13310b57cec5SDimitry Andric if (Record.size() != 2) {
13320b57cec5SDimitry Andric dropRecord();
13330b57cec5SDimitry Andric break;
13340b57cec5SDimitry Andric }
13350b57cec5SDimitry Andric
133681ad6265SDimitry Andric unsigned TyID = Record[0];
1337bdd1243dSDimitry Andric Type *Ty = Callbacks.GetTypeByID(TyID);
1338c9157d92SDimitry Andric if (!Ty || Ty->isMetadataTy() || Ty->isVoidTy()) {
13390b57cec5SDimitry Andric dropRecord();
13400b57cec5SDimitry Andric break;
13410b57cec5SDimitry Andric }
13420b57cec5SDimitry Andric
1343fcaf7f86SDimitry Andric Value *V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1344fcaf7f86SDimitry Andric /*ConstExprInsertBB*/ nullptr);
1345fcaf7f86SDimitry Andric if (!V)
1346fcaf7f86SDimitry Andric return error("Invalid value reference from old fn metadata");
1347fcaf7f86SDimitry Andric
1348fcaf7f86SDimitry Andric MetadataList.assignValue(LocalAsMetadata::get(V), NextMetadataNo);
13490b57cec5SDimitry Andric NextMetadataNo++;
13500b57cec5SDimitry Andric break;
13510b57cec5SDimitry Andric }
13520b57cec5SDimitry Andric case bitc::METADATA_OLD_NODE: {
13535ffd83dbSDimitry Andric // Deprecated, but still needed to read old bitcode files.
13540b57cec5SDimitry Andric if (Record.size() % 2 == 1)
13550b57cec5SDimitry Andric return error("Invalid record");
13560b57cec5SDimitry Andric
13570b57cec5SDimitry Andric unsigned Size = Record.size();
13580b57cec5SDimitry Andric SmallVector<Metadata *, 8> Elts;
13590b57cec5SDimitry Andric for (unsigned i = 0; i != Size; i += 2) {
136081ad6265SDimitry Andric unsigned TyID = Record[i];
1361bdd1243dSDimitry Andric Type *Ty = Callbacks.GetTypeByID(TyID);
13620b57cec5SDimitry Andric if (!Ty)
13630b57cec5SDimitry Andric return error("Invalid record");
13640b57cec5SDimitry Andric if (Ty->isMetadataTy())
13650b57cec5SDimitry Andric Elts.push_back(getMD(Record[i + 1]));
13660b57cec5SDimitry Andric else if (!Ty->isVoidTy()) {
1367c9157d92SDimitry Andric Value *V = getValueFwdRef(ValueList, Record[i + 1], Ty, TyID);
1368fcaf7f86SDimitry Andric if (!V)
1369fcaf7f86SDimitry Andric return error("Invalid value reference from old metadata");
1370bdd1243dSDimitry Andric Metadata *MD = ValueAsMetadata::get(V);
13710b57cec5SDimitry Andric assert(isa<ConstantAsMetadata>(MD) &&
13720b57cec5SDimitry Andric "Expected non-function-local metadata");
1373bdd1243dSDimitry Andric callMDTypeCallback(&MD, TyID);
13740b57cec5SDimitry Andric Elts.push_back(MD);
13750b57cec5SDimitry Andric } else
13760b57cec5SDimitry Andric Elts.push_back(nullptr);
13770b57cec5SDimitry Andric }
13780b57cec5SDimitry Andric MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
13790b57cec5SDimitry Andric NextMetadataNo++;
13800b57cec5SDimitry Andric break;
13810b57cec5SDimitry Andric }
13820b57cec5SDimitry Andric case bitc::METADATA_VALUE: {
13830b57cec5SDimitry Andric if (Record.size() != 2)
13840b57cec5SDimitry Andric return error("Invalid record");
13850b57cec5SDimitry Andric
138681ad6265SDimitry Andric unsigned TyID = Record[0];
1387bdd1243dSDimitry Andric Type *Ty = Callbacks.GetTypeByID(TyID);
1388c9157d92SDimitry Andric if (!Ty || Ty->isMetadataTy() || Ty->isVoidTy())
13890b57cec5SDimitry Andric return error("Invalid record");
13900b57cec5SDimitry Andric
1391c9157d92SDimitry Andric Value *V = getValueFwdRef(ValueList, Record[1], Ty, TyID);
1392fcaf7f86SDimitry Andric if (!V)
1393fcaf7f86SDimitry Andric return error("Invalid value reference from metadata");
1394fcaf7f86SDimitry Andric
1395bdd1243dSDimitry Andric Metadata *MD = ValueAsMetadata::get(V);
1396bdd1243dSDimitry Andric callMDTypeCallback(&MD, TyID);
1397bdd1243dSDimitry Andric MetadataList.assignValue(MD, NextMetadataNo);
13980b57cec5SDimitry Andric NextMetadataNo++;
13990b57cec5SDimitry Andric break;
14000b57cec5SDimitry Andric }
14010b57cec5SDimitry Andric case bitc::METADATA_DISTINCT_NODE:
14020b57cec5SDimitry Andric IsDistinct = true;
1403bdd1243dSDimitry Andric [[fallthrough]];
14040b57cec5SDimitry Andric case bitc::METADATA_NODE: {
14050b57cec5SDimitry Andric SmallVector<Metadata *, 8> Elts;
14060b57cec5SDimitry Andric Elts.reserve(Record.size());
14070b57cec5SDimitry Andric for (unsigned ID : Record)
14080b57cec5SDimitry Andric Elts.push_back(getMDOrNull(ID));
14090b57cec5SDimitry Andric MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
14100b57cec5SDimitry Andric : MDNode::get(Context, Elts),
14110b57cec5SDimitry Andric NextMetadataNo);
14120b57cec5SDimitry Andric NextMetadataNo++;
14130b57cec5SDimitry Andric break;
14140b57cec5SDimitry Andric }
14150b57cec5SDimitry Andric case bitc::METADATA_LOCATION: {
14160b57cec5SDimitry Andric if (Record.size() != 5 && Record.size() != 6)
14170b57cec5SDimitry Andric return error("Invalid record");
14180b57cec5SDimitry Andric
14190b57cec5SDimitry Andric IsDistinct = Record[0];
14200b57cec5SDimitry Andric unsigned Line = Record[1];
14210b57cec5SDimitry Andric unsigned Column = Record[2];
14220b57cec5SDimitry Andric Metadata *Scope = getMD(Record[3]);
14230b57cec5SDimitry Andric Metadata *InlinedAt = getMDOrNull(Record[4]);
14240b57cec5SDimitry Andric bool ImplicitCode = Record.size() == 6 && Record[5];
14250b57cec5SDimitry Andric MetadataList.assignValue(
14260b57cec5SDimitry Andric GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt,
14270b57cec5SDimitry Andric ImplicitCode)),
14280b57cec5SDimitry Andric NextMetadataNo);
14290b57cec5SDimitry Andric NextMetadataNo++;
14300b57cec5SDimitry Andric break;
14310b57cec5SDimitry Andric }
14320b57cec5SDimitry Andric case bitc::METADATA_GENERIC_DEBUG: {
14330b57cec5SDimitry Andric if (Record.size() < 4)
14340b57cec5SDimitry Andric return error("Invalid record");
14350b57cec5SDimitry Andric
14360b57cec5SDimitry Andric IsDistinct = Record[0];
14370b57cec5SDimitry Andric unsigned Tag = Record[1];
14380b57cec5SDimitry Andric unsigned Version = Record[2];
14390b57cec5SDimitry Andric
14400b57cec5SDimitry Andric if (Tag >= 1u << 16 || Version != 0)
14410b57cec5SDimitry Andric return error("Invalid record");
14420b57cec5SDimitry Andric
14430b57cec5SDimitry Andric auto *Header = getMDString(Record[3]);
14440b57cec5SDimitry Andric SmallVector<Metadata *, 8> DwarfOps;
14450b57cec5SDimitry Andric for (unsigned I = 4, E = Record.size(); I != E; ++I)
14460b57cec5SDimitry Andric DwarfOps.push_back(getMDOrNull(Record[I]));
14470b57cec5SDimitry Andric MetadataList.assignValue(
14480b57cec5SDimitry Andric GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
14490b57cec5SDimitry Andric NextMetadataNo);
14500b57cec5SDimitry Andric NextMetadataNo++;
14510b57cec5SDimitry Andric break;
14520b57cec5SDimitry Andric }
14530b57cec5SDimitry Andric case bitc::METADATA_SUBRANGE: {
14540b57cec5SDimitry Andric Metadata *Val = nullptr;
14550b57cec5SDimitry Andric // Operand 'count' is interpreted as:
14560b57cec5SDimitry Andric // - Signed integer (version 0)
14570b57cec5SDimitry Andric // - Metadata node (version 1)
14585ffd83dbSDimitry Andric // Operand 'lowerBound' is interpreted as:
14595ffd83dbSDimitry Andric // - Signed integer (version 0 and 1)
14605ffd83dbSDimitry Andric // - Metadata node (version 2)
14615ffd83dbSDimitry Andric // Operands 'upperBound' and 'stride' are interpreted as:
14625ffd83dbSDimitry Andric // - Metadata node (version 2)
14630b57cec5SDimitry Andric switch (Record[0] >> 1) {
14640b57cec5SDimitry Andric case 0:
14650b57cec5SDimitry Andric Val = GET_OR_DISTINCT(DISubrange,
14665ffd83dbSDimitry Andric (Context, Record[1], unrotateSign(Record[2])));
14670b57cec5SDimitry Andric break;
14680b57cec5SDimitry Andric case 1:
14690b57cec5SDimitry Andric Val = GET_OR_DISTINCT(DISubrange, (Context, getMDOrNull(Record[1]),
14705ffd83dbSDimitry Andric unrotateSign(Record[2])));
14715ffd83dbSDimitry Andric break;
14725ffd83dbSDimitry Andric case 2:
14735ffd83dbSDimitry Andric Val = GET_OR_DISTINCT(
14745ffd83dbSDimitry Andric DISubrange, (Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
14755ffd83dbSDimitry Andric getMDOrNull(Record[3]), getMDOrNull(Record[4])));
14760b57cec5SDimitry Andric break;
14770b57cec5SDimitry Andric default:
14780b57cec5SDimitry Andric return error("Invalid record: Unsupported version of DISubrange");
14790b57cec5SDimitry Andric }
14800b57cec5SDimitry Andric
14810b57cec5SDimitry Andric MetadataList.assignValue(Val, NextMetadataNo);
14820b57cec5SDimitry Andric IsDistinct = Record[0] & 1;
14830b57cec5SDimitry Andric NextMetadataNo++;
14840b57cec5SDimitry Andric break;
14850b57cec5SDimitry Andric }
1486e8d8bef9SDimitry Andric case bitc::METADATA_GENERIC_SUBRANGE: {
1487e8d8bef9SDimitry Andric Metadata *Val = nullptr;
1488e8d8bef9SDimitry Andric Val = GET_OR_DISTINCT(DIGenericSubrange,
1489e8d8bef9SDimitry Andric (Context, getMDOrNull(Record[1]),
1490e8d8bef9SDimitry Andric getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1491e8d8bef9SDimitry Andric getMDOrNull(Record[4])));
1492e8d8bef9SDimitry Andric
1493e8d8bef9SDimitry Andric MetadataList.assignValue(Val, NextMetadataNo);
1494e8d8bef9SDimitry Andric IsDistinct = Record[0] & 1;
1495e8d8bef9SDimitry Andric NextMetadataNo++;
1496e8d8bef9SDimitry Andric break;
1497e8d8bef9SDimitry Andric }
14980b57cec5SDimitry Andric case bitc::METADATA_ENUMERATOR: {
14995ffd83dbSDimitry Andric if (Record.size() < 3)
15000b57cec5SDimitry Andric return error("Invalid record");
15010b57cec5SDimitry Andric
15020b57cec5SDimitry Andric IsDistinct = Record[0] & 1;
15030b57cec5SDimitry Andric bool IsUnsigned = Record[0] & 2;
15045ffd83dbSDimitry Andric bool IsBigInt = Record[0] & 4;
15055ffd83dbSDimitry Andric APInt Value;
15065ffd83dbSDimitry Andric
15075ffd83dbSDimitry Andric if (IsBigInt) {
15085ffd83dbSDimitry Andric const uint64_t BitWidth = Record[1];
15095ffd83dbSDimitry Andric const size_t NumWords = Record.size() - 3;
1510bdd1243dSDimitry Andric Value = readWideAPInt(ArrayRef(&Record[3], NumWords), BitWidth);
15115ffd83dbSDimitry Andric } else
15125ffd83dbSDimitry Andric Value = APInt(64, unrotateSign(Record[1]), !IsUnsigned);
15135ffd83dbSDimitry Andric
15140b57cec5SDimitry Andric MetadataList.assignValue(
15155ffd83dbSDimitry Andric GET_OR_DISTINCT(DIEnumerator,
15165ffd83dbSDimitry Andric (Context, Value, IsUnsigned, getMDString(Record[2]))),
15170b57cec5SDimitry Andric NextMetadataNo);
15180b57cec5SDimitry Andric NextMetadataNo++;
15190b57cec5SDimitry Andric break;
15200b57cec5SDimitry Andric }
15210b57cec5SDimitry Andric case bitc::METADATA_BASIC_TYPE: {
15220b57cec5SDimitry Andric if (Record.size() < 6 || Record.size() > 7)
15230b57cec5SDimitry Andric return error("Invalid record");
15240b57cec5SDimitry Andric
15250b57cec5SDimitry Andric IsDistinct = Record[0];
1526349cc55cSDimitry Andric DINode::DIFlags Flags = (Record.size() > 6)
1527349cc55cSDimitry Andric ? static_cast<DINode::DIFlags>(Record[6])
1528349cc55cSDimitry Andric : DINode::FlagZero;
15290b57cec5SDimitry Andric
15300b57cec5SDimitry Andric MetadataList.assignValue(
15310b57cec5SDimitry Andric GET_OR_DISTINCT(DIBasicType,
15320b57cec5SDimitry Andric (Context, Record[1], getMDString(Record[2]), Record[3],
15330b57cec5SDimitry Andric Record[4], Record[5], Flags)),
15340b57cec5SDimitry Andric NextMetadataNo);
15350b57cec5SDimitry Andric NextMetadataNo++;
15360b57cec5SDimitry Andric break;
15370b57cec5SDimitry Andric }
1538e8d8bef9SDimitry Andric case bitc::METADATA_STRING_TYPE: {
153904eeddc0SDimitry Andric if (Record.size() > 9 || Record.size() < 8)
1540e8d8bef9SDimitry Andric return error("Invalid record");
1541e8d8bef9SDimitry Andric
1542e8d8bef9SDimitry Andric IsDistinct = Record[0];
154304eeddc0SDimitry Andric bool SizeIs8 = Record.size() == 8;
154404eeddc0SDimitry Andric // StringLocationExp (i.e. Record[5]) is added at a later time
154504eeddc0SDimitry Andric // than the other fields. The code here enables backward compatibility.
154604eeddc0SDimitry Andric Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
154704eeddc0SDimitry Andric unsigned Offset = SizeIs8 ? 5 : 6;
1548e8d8bef9SDimitry Andric MetadataList.assignValue(
1549e8d8bef9SDimitry Andric GET_OR_DISTINCT(DIStringType,
1550e8d8bef9SDimitry Andric (Context, Record[1], getMDString(Record[2]),
1551e8d8bef9SDimitry Andric getMDOrNull(Record[3]), getMDOrNull(Record[4]),
155204eeddc0SDimitry Andric StringLocationExp, Record[Offset], Record[Offset + 1],
155304eeddc0SDimitry Andric Record[Offset + 2])),
1554e8d8bef9SDimitry Andric NextMetadataNo);
1555e8d8bef9SDimitry Andric NextMetadataNo++;
1556e8d8bef9SDimitry Andric break;
1557e8d8bef9SDimitry Andric }
15580b57cec5SDimitry Andric case bitc::METADATA_DERIVED_TYPE: {
1559349cc55cSDimitry Andric if (Record.size() < 12 || Record.size() > 14)
15600b57cec5SDimitry Andric return error("Invalid record");
15610b57cec5SDimitry Andric
15620b57cec5SDimitry Andric // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
15630b57cec5SDimitry Andric // that there is no DWARF address space associated with DIDerivedType.
1564bdd1243dSDimitry Andric std::optional<unsigned> DWARFAddressSpace;
15650b57cec5SDimitry Andric if (Record.size() > 12 && Record[12])
15660b57cec5SDimitry Andric DWARFAddressSpace = Record[12] - 1;
15670b57cec5SDimitry Andric
1568349cc55cSDimitry Andric Metadata *Annotations = nullptr;
1569349cc55cSDimitry Andric if (Record.size() > 13 && Record[13])
1570349cc55cSDimitry Andric Annotations = getMDOrNull(Record[13]);
1571349cc55cSDimitry Andric
15720b57cec5SDimitry Andric IsDistinct = Record[0];
15730b57cec5SDimitry Andric DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
15740b57cec5SDimitry Andric MetadataList.assignValue(
15750b57cec5SDimitry Andric GET_OR_DISTINCT(DIDerivedType,
15760b57cec5SDimitry Andric (Context, Record[1], getMDString(Record[2]),
15770b57cec5SDimitry Andric getMDOrNull(Record[3]), Record[4],
15780b57cec5SDimitry Andric getDITypeRefOrNull(Record[5]),
15790b57cec5SDimitry Andric getDITypeRefOrNull(Record[6]), Record[7], Record[8],
15800b57cec5SDimitry Andric Record[9], DWARFAddressSpace, Flags,
1581349cc55cSDimitry Andric getDITypeRefOrNull(Record[11]), Annotations)),
15820b57cec5SDimitry Andric NextMetadataNo);
15830b57cec5SDimitry Andric NextMetadataNo++;
15840b57cec5SDimitry Andric break;
15850b57cec5SDimitry Andric }
15860b57cec5SDimitry Andric case bitc::METADATA_COMPOSITE_TYPE: {
1587349cc55cSDimitry Andric if (Record.size() < 16 || Record.size() > 22)
15880b57cec5SDimitry Andric return error("Invalid record");
15890b57cec5SDimitry Andric
15900b57cec5SDimitry Andric // If we have a UUID and this is not a forward declaration, lookup the
15910b57cec5SDimitry Andric // mapping.
15920b57cec5SDimitry Andric IsDistinct = Record[0] & 0x1;
15930b57cec5SDimitry Andric bool IsNotUsedInTypeRef = Record[0] >= 2;
15940b57cec5SDimitry Andric unsigned Tag = Record[1];
15950b57cec5SDimitry Andric MDString *Name = getMDString(Record[2]);
15960b57cec5SDimitry Andric Metadata *File = getMDOrNull(Record[3]);
15970b57cec5SDimitry Andric unsigned Line = Record[4];
15980b57cec5SDimitry Andric Metadata *Scope = getDITypeRefOrNull(Record[5]);
15990b57cec5SDimitry Andric Metadata *BaseType = nullptr;
16000b57cec5SDimitry Andric uint64_t SizeInBits = Record[7];
16010b57cec5SDimitry Andric if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
16020b57cec5SDimitry Andric return error("Alignment value is too large");
16030b57cec5SDimitry Andric uint32_t AlignInBits = Record[8];
16040b57cec5SDimitry Andric uint64_t OffsetInBits = 0;
16050b57cec5SDimitry Andric DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
16060b57cec5SDimitry Andric Metadata *Elements = nullptr;
16070b57cec5SDimitry Andric unsigned RuntimeLang = Record[12];
16080b57cec5SDimitry Andric Metadata *VTableHolder = nullptr;
16090b57cec5SDimitry Andric Metadata *TemplateParams = nullptr;
16100b57cec5SDimitry Andric Metadata *Discriminator = nullptr;
16115ffd83dbSDimitry Andric Metadata *DataLocation = nullptr;
1612e8d8bef9SDimitry Andric Metadata *Associated = nullptr;
1613e8d8bef9SDimitry Andric Metadata *Allocated = nullptr;
1614e8d8bef9SDimitry Andric Metadata *Rank = nullptr;
1615349cc55cSDimitry Andric Metadata *Annotations = nullptr;
16160b57cec5SDimitry Andric auto *Identifier = getMDString(Record[15]);
16170b57cec5SDimitry Andric // If this module is being parsed so that it can be ThinLTO imported
1618*a58f00eaSDimitry Andric // into another module, composite types only need to be imported as
1619*a58f00eaSDimitry Andric // type declarations (unless full type definitions are requested).
1620*a58f00eaSDimitry Andric // Create type declarations up front to save memory. This is only
1621*a58f00eaSDimitry Andric // done for types which have an Identifier, and are therefore
1622*a58f00eaSDimitry Andric // subject to the ODR.
1623*a58f00eaSDimitry Andric //
1624*a58f00eaSDimitry Andric // buildODRType handles the case where this is type ODRed with a
1625*a58f00eaSDimitry Andric // definition needed by the importing module, in which case the
1626*a58f00eaSDimitry Andric // existing definition is used.
1627*a58f00eaSDimitry Andric //
1628*a58f00eaSDimitry Andric // We always import full definitions for anonymous composite types,
1629*a58f00eaSDimitry Andric // as without a name, debuggers cannot easily resolve a declaration
1630*a58f00eaSDimitry Andric // to its definition.
1631*a58f00eaSDimitry Andric if (IsImporting && !ImportFullTypeDefinitions && Identifier && Name &&
16320b57cec5SDimitry Andric (Tag == dwarf::DW_TAG_enumeration_type ||
16330b57cec5SDimitry Andric Tag == dwarf::DW_TAG_class_type ||
16340b57cec5SDimitry Andric Tag == dwarf::DW_TAG_structure_type ||
16350b57cec5SDimitry Andric Tag == dwarf::DW_TAG_union_type)) {
16360b57cec5SDimitry Andric Flags = Flags | DINode::FlagFwdDecl;
163781ad6265SDimitry Andric // This is a hack around preserving template parameters for simplified
163881ad6265SDimitry Andric // template names - it should probably be replaced with a
163981ad6265SDimitry Andric // DICompositeType flag specifying whether template parameters are
164081ad6265SDimitry Andric // required on declarations of this type.
164181ad6265SDimitry Andric StringRef NameStr = Name->getString();
1642c9157d92SDimitry Andric if (!NameStr.contains('<') || NameStr.starts_with("_STN|"))
164381ad6265SDimitry Andric TemplateParams = getMDOrNull(Record[14]);
16440b57cec5SDimitry Andric } else {
16450b57cec5SDimitry Andric BaseType = getDITypeRefOrNull(Record[6]);
16460b57cec5SDimitry Andric OffsetInBits = Record[9];
16470b57cec5SDimitry Andric Elements = getMDOrNull(Record[11]);
16480b57cec5SDimitry Andric VTableHolder = getDITypeRefOrNull(Record[13]);
16490b57cec5SDimitry Andric TemplateParams = getMDOrNull(Record[14]);
16500b57cec5SDimitry Andric if (Record.size() > 16)
16510b57cec5SDimitry Andric Discriminator = getMDOrNull(Record[16]);
16525ffd83dbSDimitry Andric if (Record.size() > 17)
16535ffd83dbSDimitry Andric DataLocation = getMDOrNull(Record[17]);
1654e8d8bef9SDimitry Andric if (Record.size() > 19) {
1655e8d8bef9SDimitry Andric Associated = getMDOrNull(Record[18]);
1656e8d8bef9SDimitry Andric Allocated = getMDOrNull(Record[19]);
1657e8d8bef9SDimitry Andric }
1658e8d8bef9SDimitry Andric if (Record.size() > 20) {
1659e8d8bef9SDimitry Andric Rank = getMDOrNull(Record[20]);
1660e8d8bef9SDimitry Andric }
1661349cc55cSDimitry Andric if (Record.size() > 21) {
1662349cc55cSDimitry Andric Annotations = getMDOrNull(Record[21]);
1663349cc55cSDimitry Andric }
16640b57cec5SDimitry Andric }
16650b57cec5SDimitry Andric DICompositeType *CT = nullptr;
16660b57cec5SDimitry Andric if (Identifier)
16670b57cec5SDimitry Andric CT = DICompositeType::buildODRType(
16680b57cec5SDimitry Andric Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
16690b57cec5SDimitry Andric SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1670e8d8bef9SDimitry Andric VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1671349cc55cSDimitry Andric Allocated, Rank, Annotations);
16720b57cec5SDimitry Andric
16730b57cec5SDimitry Andric // Create a node if we didn't get a lazy ODR type.
16740b57cec5SDimitry Andric if (!CT)
16750b57cec5SDimitry Andric CT = GET_OR_DISTINCT(DICompositeType,
16760b57cec5SDimitry Andric (Context, Tag, Name, File, Line, Scope, BaseType,
16770b57cec5SDimitry Andric SizeInBits, AlignInBits, OffsetInBits, Flags,
16780b57cec5SDimitry Andric Elements, RuntimeLang, VTableHolder, TemplateParams,
1679e8d8bef9SDimitry Andric Identifier, Discriminator, DataLocation, Associated,
1680349cc55cSDimitry Andric Allocated, Rank, Annotations));
16810b57cec5SDimitry Andric if (!IsNotUsedInTypeRef && Identifier)
16820b57cec5SDimitry Andric MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
16830b57cec5SDimitry Andric
16840b57cec5SDimitry Andric MetadataList.assignValue(CT, NextMetadataNo);
16850b57cec5SDimitry Andric NextMetadataNo++;
16860b57cec5SDimitry Andric break;
16870b57cec5SDimitry Andric }
16880b57cec5SDimitry Andric case bitc::METADATA_SUBROUTINE_TYPE: {
16890b57cec5SDimitry Andric if (Record.size() < 3 || Record.size() > 4)
16900b57cec5SDimitry Andric return error("Invalid record");
16910b57cec5SDimitry Andric bool IsOldTypeRefArray = Record[0] < 2;
16920b57cec5SDimitry Andric unsigned CC = (Record.size() > 3) ? Record[3] : 0;
16930b57cec5SDimitry Andric
16940b57cec5SDimitry Andric IsDistinct = Record[0] & 0x1;
16950b57cec5SDimitry Andric DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
16960b57cec5SDimitry Andric Metadata *Types = getMDOrNull(Record[2]);
16970b57cec5SDimitry Andric if (LLVM_UNLIKELY(IsOldTypeRefArray))
16980b57cec5SDimitry Andric Types = MetadataList.upgradeTypeRefArray(Types);
16990b57cec5SDimitry Andric
17000b57cec5SDimitry Andric MetadataList.assignValue(
17010b57cec5SDimitry Andric GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
17020b57cec5SDimitry Andric NextMetadataNo);
17030b57cec5SDimitry Andric NextMetadataNo++;
17040b57cec5SDimitry Andric break;
17050b57cec5SDimitry Andric }
17060b57cec5SDimitry Andric
17070b57cec5SDimitry Andric case bitc::METADATA_MODULE: {
1708e8d8bef9SDimitry Andric if (Record.size() < 5 || Record.size() > 9)
17090b57cec5SDimitry Andric return error("Invalid record");
17100b57cec5SDimitry Andric
1711e8d8bef9SDimitry Andric unsigned Offset = Record.size() >= 8 ? 2 : 1;
17120b57cec5SDimitry Andric IsDistinct = Record[0];
17130b57cec5SDimitry Andric MetadataList.assignValue(
17145ffd83dbSDimitry Andric GET_OR_DISTINCT(
17155ffd83dbSDimitry Andric DIModule,
1716e8d8bef9SDimitry Andric (Context, Record.size() >= 8 ? getMDOrNull(Record[1]) : nullptr,
17175ffd83dbSDimitry Andric getMDOrNull(Record[0 + Offset]), getMDString(Record[1 + Offset]),
17185ffd83dbSDimitry Andric getMDString(Record[2 + Offset]), getMDString(Record[3 + Offset]),
17195ffd83dbSDimitry Andric getMDString(Record[4 + Offset]),
1720e8d8bef9SDimitry Andric Record.size() <= 7 ? 0 : Record[7],
1721e8d8bef9SDimitry Andric Record.size() <= 8 ? false : Record[8])),
17220b57cec5SDimitry Andric NextMetadataNo);
17230b57cec5SDimitry Andric NextMetadataNo++;
17240b57cec5SDimitry Andric break;
17250b57cec5SDimitry Andric }
17260b57cec5SDimitry Andric
17270b57cec5SDimitry Andric case bitc::METADATA_FILE: {
17280b57cec5SDimitry Andric if (Record.size() != 3 && Record.size() != 5 && Record.size() != 6)
17290b57cec5SDimitry Andric return error("Invalid record");
17300b57cec5SDimitry Andric
17310b57cec5SDimitry Andric IsDistinct = Record[0];
1732bdd1243dSDimitry Andric std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
17330b57cec5SDimitry Andric // The BitcodeWriter writes null bytes into Record[3:4] when the Checksum
17340b57cec5SDimitry Andric // is not present. This matches up with the old internal representation,
17350b57cec5SDimitry Andric // and the old encoding for CSK_None in the ChecksumKind. The new
17360b57cec5SDimitry Andric // representation reserves the value 0 in the ChecksumKind to continue to
17370b57cec5SDimitry Andric // encode None in a backwards-compatible way.
17380b57cec5SDimitry Andric if (Record.size() > 4 && Record[3] && Record[4])
17390b57cec5SDimitry Andric Checksum.emplace(static_cast<DIFile::ChecksumKind>(Record[3]),
17400b57cec5SDimitry Andric getMDString(Record[4]));
17410b57cec5SDimitry Andric MetadataList.assignValue(
1742bdd1243dSDimitry Andric GET_OR_DISTINCT(DIFile,
1743bdd1243dSDimitry Andric (Context, getMDString(Record[1]),
1744bdd1243dSDimitry Andric getMDString(Record[2]), Checksum,
1745bdd1243dSDimitry Andric Record.size() > 5 ? getMDString(Record[5]) : nullptr)),
17460b57cec5SDimitry Andric NextMetadataNo);
17470b57cec5SDimitry Andric NextMetadataNo++;
17480b57cec5SDimitry Andric break;
17490b57cec5SDimitry Andric }
17500b57cec5SDimitry Andric case bitc::METADATA_COMPILE_UNIT: {
17515ffd83dbSDimitry Andric if (Record.size() < 14 || Record.size() > 22)
17520b57cec5SDimitry Andric return error("Invalid record");
17530b57cec5SDimitry Andric
17540b57cec5SDimitry Andric // Ignore Record[0], which indicates whether this compile unit is
17550b57cec5SDimitry Andric // distinct. It's always distinct.
17560b57cec5SDimitry Andric IsDistinct = true;
17570b57cec5SDimitry Andric auto *CU = DICompileUnit::getDistinct(
17580b57cec5SDimitry Andric Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
17590b57cec5SDimitry Andric Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
17600b57cec5SDimitry Andric Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
17610b57cec5SDimitry Andric getMDOrNull(Record[12]), getMDOrNull(Record[13]),
17620b57cec5SDimitry Andric Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
17630b57cec5SDimitry Andric Record.size() <= 14 ? 0 : Record[14],
17640b57cec5SDimitry Andric Record.size() <= 16 ? true : Record[16],
17650b57cec5SDimitry Andric Record.size() <= 17 ? false : Record[17],
17660b57cec5SDimitry Andric Record.size() <= 18 ? 0 : Record[18],
176704eeddc0SDimitry Andric Record.size() <= 19 ? false : Record[19],
17685ffd83dbSDimitry Andric Record.size() <= 20 ? nullptr : getMDString(Record[20]),
17695ffd83dbSDimitry Andric Record.size() <= 21 ? nullptr : getMDString(Record[21]));
17700b57cec5SDimitry Andric
17710b57cec5SDimitry Andric MetadataList.assignValue(CU, NextMetadataNo);
17720b57cec5SDimitry Andric NextMetadataNo++;
17730b57cec5SDimitry Andric
17740b57cec5SDimitry Andric // Move the Upgrade the list of subprograms.
17750b57cec5SDimitry Andric if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
17760b57cec5SDimitry Andric CUSubprograms.push_back({CU, SPs});
17770b57cec5SDimitry Andric break;
17780b57cec5SDimitry Andric }
17790b57cec5SDimitry Andric case bitc::METADATA_SUBPROGRAM: {
17800b57cec5SDimitry Andric if (Record.size() < 18 || Record.size() > 21)
17810b57cec5SDimitry Andric return error("Invalid record");
17820b57cec5SDimitry Andric
17830b57cec5SDimitry Andric bool HasSPFlags = Record[0] & 4;
17840b57cec5SDimitry Andric
17850b57cec5SDimitry Andric DINode::DIFlags Flags;
17860b57cec5SDimitry Andric DISubprogram::DISPFlags SPFlags;
17870b57cec5SDimitry Andric if (!HasSPFlags)
17880b57cec5SDimitry Andric Flags = static_cast<DINode::DIFlags>(Record[11 + 2]);
17890b57cec5SDimitry Andric else {
17900b57cec5SDimitry Andric Flags = static_cast<DINode::DIFlags>(Record[11]);
17910b57cec5SDimitry Andric SPFlags = static_cast<DISubprogram::DISPFlags>(Record[9]);
17920b57cec5SDimitry Andric }
17930b57cec5SDimitry Andric
17940b57cec5SDimitry Andric // Support for old metadata when
17950b57cec5SDimitry Andric // subprogram specific flags are placed in DIFlags.
17960b57cec5SDimitry Andric const unsigned DIFlagMainSubprogram = 1 << 21;
17970b57cec5SDimitry Andric bool HasOldMainSubprogramFlag = Flags & DIFlagMainSubprogram;
17980b57cec5SDimitry Andric if (HasOldMainSubprogramFlag)
17990b57cec5SDimitry Andric // Remove old DIFlagMainSubprogram from DIFlags.
18000b57cec5SDimitry Andric // Note: This assumes that any future use of bit 21 defaults to it
18010b57cec5SDimitry Andric // being 0.
18020b57cec5SDimitry Andric Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
18030b57cec5SDimitry Andric
18040b57cec5SDimitry Andric if (HasOldMainSubprogramFlag && HasSPFlags)
18050b57cec5SDimitry Andric SPFlags |= DISubprogram::SPFlagMainSubprogram;
18060b57cec5SDimitry Andric else if (!HasSPFlags)
18070b57cec5SDimitry Andric SPFlags = DISubprogram::toSPFlags(
18080b57cec5SDimitry Andric /*IsLocalToUnit=*/Record[7], /*IsDefinition=*/Record[8],
18090b57cec5SDimitry Andric /*IsOptimized=*/Record[14], /*Virtuality=*/Record[11],
181004eeddc0SDimitry Andric /*IsMainSubprogram=*/HasOldMainSubprogramFlag);
18110b57cec5SDimitry Andric
18120b57cec5SDimitry Andric // All definitions should be distinct.
18130b57cec5SDimitry Andric IsDistinct = (Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
18140b57cec5SDimitry Andric // Version 1 has a Function as Record[15].
18150b57cec5SDimitry Andric // Version 2 has removed Record[15].
18160b57cec5SDimitry Andric // Version 3 has the Unit as Record[15].
18170b57cec5SDimitry Andric // Version 4 added thisAdjustment.
18180b57cec5SDimitry Andric // Version 5 repacked flags into DISPFlags, changing many element numbers.
18190b57cec5SDimitry Andric bool HasUnit = Record[0] & 2;
18200b57cec5SDimitry Andric if (!HasSPFlags && HasUnit && Record.size() < 19)
18210b57cec5SDimitry Andric return error("Invalid record");
18220b57cec5SDimitry Andric if (HasSPFlags && !HasUnit)
18230b57cec5SDimitry Andric return error("Invalid record");
18240b57cec5SDimitry Andric // Accommodate older formats.
18250b57cec5SDimitry Andric bool HasFn = false;
18260b57cec5SDimitry Andric bool HasThisAdj = true;
18270b57cec5SDimitry Andric bool HasThrownTypes = true;
1828349cc55cSDimitry Andric bool HasAnnotations = false;
182981ad6265SDimitry Andric bool HasTargetFuncName = false;
18300b57cec5SDimitry Andric unsigned OffsetA = 0;
18310b57cec5SDimitry Andric unsigned OffsetB = 0;
18320b57cec5SDimitry Andric if (!HasSPFlags) {
18330b57cec5SDimitry Andric OffsetA = 2;
18340b57cec5SDimitry Andric OffsetB = 2;
18350b57cec5SDimitry Andric if (Record.size() >= 19) {
18360b57cec5SDimitry Andric HasFn = !HasUnit;
18370b57cec5SDimitry Andric OffsetB++;
18380b57cec5SDimitry Andric }
18390b57cec5SDimitry Andric HasThisAdj = Record.size() >= 20;
18400b57cec5SDimitry Andric HasThrownTypes = Record.size() >= 21;
1841349cc55cSDimitry Andric } else {
1842349cc55cSDimitry Andric HasAnnotations = Record.size() >= 19;
184381ad6265SDimitry Andric HasTargetFuncName = Record.size() >= 20;
18440b57cec5SDimitry Andric }
18450b57cec5SDimitry Andric Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
18460b57cec5SDimitry Andric DISubprogram *SP = GET_OR_DISTINCT(
18470b57cec5SDimitry Andric DISubprogram,
18480b57cec5SDimitry Andric (Context,
18490b57cec5SDimitry Andric getDITypeRefOrNull(Record[1]), // scope
18500b57cec5SDimitry Andric getMDString(Record[2]), // name
18510b57cec5SDimitry Andric getMDString(Record[3]), // linkageName
18520b57cec5SDimitry Andric getMDOrNull(Record[4]), // file
18530b57cec5SDimitry Andric Record[5], // line
18540b57cec5SDimitry Andric getMDOrNull(Record[6]), // type
18550b57cec5SDimitry Andric Record[7 + OffsetA], // scopeLine
18560b57cec5SDimitry Andric getDITypeRefOrNull(Record[8 + OffsetA]), // containingType
18570b57cec5SDimitry Andric Record[10 + OffsetA], // virtualIndex
18580b57cec5SDimitry Andric HasThisAdj ? Record[16 + OffsetB] : 0, // thisAdjustment
18590b57cec5SDimitry Andric Flags, // flags
18600b57cec5SDimitry Andric SPFlags, // SPFlags
18610b57cec5SDimitry Andric HasUnit ? CUorFn : nullptr, // unit
18620b57cec5SDimitry Andric getMDOrNull(Record[13 + OffsetB]), // templateParams
18630b57cec5SDimitry Andric getMDOrNull(Record[14 + OffsetB]), // declaration
18640b57cec5SDimitry Andric getMDOrNull(Record[15 + OffsetB]), // retainedNodes
18650b57cec5SDimitry Andric HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
1866349cc55cSDimitry Andric : nullptr, // thrownTypes
1867349cc55cSDimitry Andric HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
186881ad6265SDimitry Andric : nullptr, // annotations
186981ad6265SDimitry Andric HasTargetFuncName ? getMDString(Record[19 + OffsetB])
187081ad6265SDimitry Andric : nullptr // targetFuncName
18710b57cec5SDimitry Andric ));
18720b57cec5SDimitry Andric MetadataList.assignValue(SP, NextMetadataNo);
18730b57cec5SDimitry Andric NextMetadataNo++;
18740b57cec5SDimitry Andric
18750b57cec5SDimitry Andric // Upgrade sp->function mapping to function->sp mapping.
18760b57cec5SDimitry Andric if (HasFn) {
18770b57cec5SDimitry Andric if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
18780b57cec5SDimitry Andric if (auto *F = dyn_cast<Function>(CMD->getValue())) {
18790b57cec5SDimitry Andric if (F->isMaterializable())
18800b57cec5SDimitry Andric // Defer until materialized; unmaterialized functions may not have
18810b57cec5SDimitry Andric // metadata.
18820b57cec5SDimitry Andric FunctionsWithSPs[F] = SP;
18830b57cec5SDimitry Andric else if (!F->empty())
18840b57cec5SDimitry Andric F->setSubprogram(SP);
18850b57cec5SDimitry Andric }
18860b57cec5SDimitry Andric }
18870b57cec5SDimitry Andric break;
18880b57cec5SDimitry Andric }
18890b57cec5SDimitry Andric case bitc::METADATA_LEXICAL_BLOCK: {
18900b57cec5SDimitry Andric if (Record.size() != 5)
18910b57cec5SDimitry Andric return error("Invalid record");
18920b57cec5SDimitry Andric
18930b57cec5SDimitry Andric IsDistinct = Record[0];
18940b57cec5SDimitry Andric MetadataList.assignValue(
18950b57cec5SDimitry Andric GET_OR_DISTINCT(DILexicalBlock,
18960b57cec5SDimitry Andric (Context, getMDOrNull(Record[1]),
18970b57cec5SDimitry Andric getMDOrNull(Record[2]), Record[3], Record[4])),
18980b57cec5SDimitry Andric NextMetadataNo);
18990b57cec5SDimitry Andric NextMetadataNo++;
19000b57cec5SDimitry Andric break;
19010b57cec5SDimitry Andric }
19020b57cec5SDimitry Andric case bitc::METADATA_LEXICAL_BLOCK_FILE: {
19030b57cec5SDimitry Andric if (Record.size() != 4)
19040b57cec5SDimitry Andric return error("Invalid record");
19050b57cec5SDimitry Andric
19060b57cec5SDimitry Andric IsDistinct = Record[0];
19070b57cec5SDimitry Andric MetadataList.assignValue(
19080b57cec5SDimitry Andric GET_OR_DISTINCT(DILexicalBlockFile,
19090b57cec5SDimitry Andric (Context, getMDOrNull(Record[1]),
19100b57cec5SDimitry Andric getMDOrNull(Record[2]), Record[3])),
19110b57cec5SDimitry Andric NextMetadataNo);
19120b57cec5SDimitry Andric NextMetadataNo++;
19130b57cec5SDimitry Andric break;
19140b57cec5SDimitry Andric }
19150b57cec5SDimitry Andric case bitc::METADATA_COMMON_BLOCK: {
19160b57cec5SDimitry Andric IsDistinct = Record[0] & 1;
19170b57cec5SDimitry Andric MetadataList.assignValue(
19180b57cec5SDimitry Andric GET_OR_DISTINCT(DICommonBlock,
19190b57cec5SDimitry Andric (Context, getMDOrNull(Record[1]),
19200b57cec5SDimitry Andric getMDOrNull(Record[2]), getMDString(Record[3]),
19210b57cec5SDimitry Andric getMDOrNull(Record[4]), Record[5])),
19220b57cec5SDimitry Andric NextMetadataNo);
19230b57cec5SDimitry Andric NextMetadataNo++;
19240b57cec5SDimitry Andric break;
19250b57cec5SDimitry Andric }
19260b57cec5SDimitry Andric case bitc::METADATA_NAMESPACE: {
19270b57cec5SDimitry Andric // Newer versions of DINamespace dropped file and line.
19280b57cec5SDimitry Andric MDString *Name;
19290b57cec5SDimitry Andric if (Record.size() == 3)
19300b57cec5SDimitry Andric Name = getMDString(Record[2]);
19310b57cec5SDimitry Andric else if (Record.size() == 5)
19320b57cec5SDimitry Andric Name = getMDString(Record[3]);
19330b57cec5SDimitry Andric else
19340b57cec5SDimitry Andric return error("Invalid record");
19350b57cec5SDimitry Andric
19360b57cec5SDimitry Andric IsDistinct = Record[0] & 1;
19370b57cec5SDimitry Andric bool ExportSymbols = Record[0] & 2;
19380b57cec5SDimitry Andric MetadataList.assignValue(
19390b57cec5SDimitry Andric GET_OR_DISTINCT(DINamespace,
19400b57cec5SDimitry Andric (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
19410b57cec5SDimitry Andric NextMetadataNo);
19420b57cec5SDimitry Andric NextMetadataNo++;
19430b57cec5SDimitry Andric break;
19440b57cec5SDimitry Andric }
19450b57cec5SDimitry Andric case bitc::METADATA_MACRO: {
19460b57cec5SDimitry Andric if (Record.size() != 5)
19470b57cec5SDimitry Andric return error("Invalid record");
19480b57cec5SDimitry Andric
19490b57cec5SDimitry Andric IsDistinct = Record[0];
19500b57cec5SDimitry Andric MetadataList.assignValue(
19510b57cec5SDimitry Andric GET_OR_DISTINCT(DIMacro,
19520b57cec5SDimitry Andric (Context, Record[1], Record[2], getMDString(Record[3]),
19530b57cec5SDimitry Andric getMDString(Record[4]))),
19540b57cec5SDimitry Andric NextMetadataNo);
19550b57cec5SDimitry Andric NextMetadataNo++;
19560b57cec5SDimitry Andric break;
19570b57cec5SDimitry Andric }
19580b57cec5SDimitry Andric case bitc::METADATA_MACRO_FILE: {
19590b57cec5SDimitry Andric if (Record.size() != 5)
19600b57cec5SDimitry Andric return error("Invalid record");
19610b57cec5SDimitry Andric
19620b57cec5SDimitry Andric IsDistinct = Record[0];
19630b57cec5SDimitry Andric MetadataList.assignValue(
19640b57cec5SDimitry Andric GET_OR_DISTINCT(DIMacroFile,
19650b57cec5SDimitry Andric (Context, Record[1], Record[2], getMDOrNull(Record[3]),
19660b57cec5SDimitry Andric getMDOrNull(Record[4]))),
19670b57cec5SDimitry Andric NextMetadataNo);
19680b57cec5SDimitry Andric NextMetadataNo++;
19690b57cec5SDimitry Andric break;
19700b57cec5SDimitry Andric }
19710b57cec5SDimitry Andric case bitc::METADATA_TEMPLATE_TYPE: {
19725ffd83dbSDimitry Andric if (Record.size() < 3 || Record.size() > 4)
19730b57cec5SDimitry Andric return error("Invalid record");
19740b57cec5SDimitry Andric
19750b57cec5SDimitry Andric IsDistinct = Record[0];
19765ffd83dbSDimitry Andric MetadataList.assignValue(
19775ffd83dbSDimitry Andric GET_OR_DISTINCT(DITemplateTypeParameter,
19780b57cec5SDimitry Andric (Context, getMDString(Record[1]),
19795ffd83dbSDimitry Andric getDITypeRefOrNull(Record[2]),
19805ffd83dbSDimitry Andric (Record.size() == 4) ? getMDOrNull(Record[3])
19815ffd83dbSDimitry Andric : getMDOrNull(false))),
19820b57cec5SDimitry Andric NextMetadataNo);
19830b57cec5SDimitry Andric NextMetadataNo++;
19840b57cec5SDimitry Andric break;
19850b57cec5SDimitry Andric }
19860b57cec5SDimitry Andric case bitc::METADATA_TEMPLATE_VALUE: {
19875ffd83dbSDimitry Andric if (Record.size() < 5 || Record.size() > 6)
19880b57cec5SDimitry Andric return error("Invalid record");
19890b57cec5SDimitry Andric
19900b57cec5SDimitry Andric IsDistinct = Record[0];
19915ffd83dbSDimitry Andric
19920b57cec5SDimitry Andric MetadataList.assignValue(
19935ffd83dbSDimitry Andric GET_OR_DISTINCT(
19945ffd83dbSDimitry Andric DITemplateValueParameter,
19950b57cec5SDimitry Andric (Context, Record[1], getMDString(Record[2]),
19960b57cec5SDimitry Andric getDITypeRefOrNull(Record[3]),
19975ffd83dbSDimitry Andric (Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(false),
19985ffd83dbSDimitry Andric (Record.size() == 6) ? getMDOrNull(Record[5])
19995ffd83dbSDimitry Andric : getMDOrNull(Record[4]))),
20000b57cec5SDimitry Andric NextMetadataNo);
20010b57cec5SDimitry Andric NextMetadataNo++;
20020b57cec5SDimitry Andric break;
20030b57cec5SDimitry Andric }
20040b57cec5SDimitry Andric case bitc::METADATA_GLOBAL_VAR: {
20050b57cec5SDimitry Andric if (Record.size() < 11 || Record.size() > 13)
20060b57cec5SDimitry Andric return error("Invalid record");
20070b57cec5SDimitry Andric
20080b57cec5SDimitry Andric IsDistinct = Record[0] & 1;
20090b57cec5SDimitry Andric unsigned Version = Record[0] >> 1;
20100b57cec5SDimitry Andric
20110b57cec5SDimitry Andric if (Version == 2) {
2012349cc55cSDimitry Andric Metadata *Annotations = nullptr;
2013349cc55cSDimitry Andric if (Record.size() > 12)
2014349cc55cSDimitry Andric Annotations = getMDOrNull(Record[12]);
2015349cc55cSDimitry Andric
20160b57cec5SDimitry Andric MetadataList.assignValue(
2017349cc55cSDimitry Andric GET_OR_DISTINCT(DIGlobalVariable,
2018349cc55cSDimitry Andric (Context, getMDOrNull(Record[1]),
2019349cc55cSDimitry Andric getMDString(Record[2]), getMDString(Record[3]),
2020349cc55cSDimitry Andric getMDOrNull(Record[4]), Record[5],
20210b57cec5SDimitry Andric getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2022349cc55cSDimitry Andric getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2023349cc55cSDimitry Andric Record[11], Annotations)),
20240b57cec5SDimitry Andric NextMetadataNo);
20250b57cec5SDimitry Andric
20260b57cec5SDimitry Andric NextMetadataNo++;
20270b57cec5SDimitry Andric } else if (Version == 1) {
20280b57cec5SDimitry Andric // No upgrade necessary. A null field will be introduced to indicate
20290b57cec5SDimitry Andric // that no parameter information is available.
20300b57cec5SDimitry Andric MetadataList.assignValue(
2031349cc55cSDimitry Andric GET_OR_DISTINCT(
2032349cc55cSDimitry Andric DIGlobalVariable,
2033349cc55cSDimitry Andric (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2034349cc55cSDimitry Andric getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
20350b57cec5SDimitry Andric getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2036349cc55cSDimitry Andric getMDOrNull(Record[10]), nullptr, Record[11], nullptr)),
20370b57cec5SDimitry Andric NextMetadataNo);
20380b57cec5SDimitry Andric
20390b57cec5SDimitry Andric NextMetadataNo++;
20400b57cec5SDimitry Andric } else if (Version == 0) {
20410b57cec5SDimitry Andric // Upgrade old metadata, which stored a global variable reference or a
20420b57cec5SDimitry Andric // ConstantInt here.
20430b57cec5SDimitry Andric NeedUpgradeToDIGlobalVariableExpression = true;
20440b57cec5SDimitry Andric Metadata *Expr = getMDOrNull(Record[9]);
20450b57cec5SDimitry Andric uint32_t AlignInBits = 0;
20460b57cec5SDimitry Andric if (Record.size() > 11) {
20470b57cec5SDimitry Andric if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
20480b57cec5SDimitry Andric return error("Alignment value is too large");
20490b57cec5SDimitry Andric AlignInBits = Record[11];
20500b57cec5SDimitry Andric }
20510b57cec5SDimitry Andric GlobalVariable *Attach = nullptr;
20520b57cec5SDimitry Andric if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
20530b57cec5SDimitry Andric if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
20540b57cec5SDimitry Andric Attach = GV;
20550b57cec5SDimitry Andric Expr = nullptr;
20560b57cec5SDimitry Andric } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
20570b57cec5SDimitry Andric Expr = DIExpression::get(Context,
20580b57cec5SDimitry Andric {dwarf::DW_OP_constu, CI->getZExtValue(),
20590b57cec5SDimitry Andric dwarf::DW_OP_stack_value});
20600b57cec5SDimitry Andric } else {
20610b57cec5SDimitry Andric Expr = nullptr;
20620b57cec5SDimitry Andric }
20630b57cec5SDimitry Andric }
20640b57cec5SDimitry Andric DIGlobalVariable *DGV = GET_OR_DISTINCT(
20650b57cec5SDimitry Andric DIGlobalVariable,
20660b57cec5SDimitry Andric (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
20670b57cec5SDimitry Andric getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
20680b57cec5SDimitry Andric getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2069349cc55cSDimitry Andric getMDOrNull(Record[10]), nullptr, AlignInBits, nullptr));
20700b57cec5SDimitry Andric
20710b57cec5SDimitry Andric DIGlobalVariableExpression *DGVE = nullptr;
20720b57cec5SDimitry Andric if (Attach || Expr)
20730b57cec5SDimitry Andric DGVE = DIGlobalVariableExpression::getDistinct(
20740b57cec5SDimitry Andric Context, DGV, Expr ? Expr : DIExpression::get(Context, {}));
20750b57cec5SDimitry Andric if (Attach)
20760b57cec5SDimitry Andric Attach->addDebugInfo(DGVE);
20770b57cec5SDimitry Andric
20780b57cec5SDimitry Andric auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
20790b57cec5SDimitry Andric MetadataList.assignValue(MDNode, NextMetadataNo);
20800b57cec5SDimitry Andric NextMetadataNo++;
20810b57cec5SDimitry Andric } else
20820b57cec5SDimitry Andric return error("Invalid record");
20830b57cec5SDimitry Andric
20840b57cec5SDimitry Andric break;
20850b57cec5SDimitry Andric }
2086bdd1243dSDimitry Andric case bitc::METADATA_ASSIGN_ID: {
2087bdd1243dSDimitry Andric if (Record.size() != 1)
2088bdd1243dSDimitry Andric return error("Invalid DIAssignID record.");
2089bdd1243dSDimitry Andric
2090bdd1243dSDimitry Andric IsDistinct = Record[0] & 1;
2091bdd1243dSDimitry Andric if (!IsDistinct)
2092bdd1243dSDimitry Andric return error("Invalid DIAssignID record. Must be distinct");
2093bdd1243dSDimitry Andric
2094bdd1243dSDimitry Andric MetadataList.assignValue(DIAssignID::getDistinct(Context), NextMetadataNo);
2095bdd1243dSDimitry Andric NextMetadataNo++;
2096bdd1243dSDimitry Andric break;
2097bdd1243dSDimitry Andric }
20980b57cec5SDimitry Andric case bitc::METADATA_LOCAL_VAR: {
20990b57cec5SDimitry Andric // 10th field is for the obseleted 'inlinedAt:' field.
21000b57cec5SDimitry Andric if (Record.size() < 8 || Record.size() > 10)
21010b57cec5SDimitry Andric return error("Invalid record");
21020b57cec5SDimitry Andric
21030b57cec5SDimitry Andric IsDistinct = Record[0] & 1;
21040b57cec5SDimitry Andric bool HasAlignment = Record[0] & 2;
21050b57cec5SDimitry Andric // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
21060b57cec5SDimitry Andric // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
21070b57cec5SDimitry Andric // this is newer version of record which doesn't have artificial tag.
21080b57cec5SDimitry Andric bool HasTag = !HasAlignment && Record.size() > 8;
21090b57cec5SDimitry Andric DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
21100b57cec5SDimitry Andric uint32_t AlignInBits = 0;
2111349cc55cSDimitry Andric Metadata *Annotations = nullptr;
21120b57cec5SDimitry Andric if (HasAlignment) {
2113349cc55cSDimitry Andric if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
21140b57cec5SDimitry Andric return error("Alignment value is too large");
2115349cc55cSDimitry Andric AlignInBits = Record[8];
2116349cc55cSDimitry Andric if (Record.size() > 9)
2117349cc55cSDimitry Andric Annotations = getMDOrNull(Record[9]);
21180b57cec5SDimitry Andric }
2119349cc55cSDimitry Andric
21200b57cec5SDimitry Andric MetadataList.assignValue(
21210b57cec5SDimitry Andric GET_OR_DISTINCT(DILocalVariable,
21220b57cec5SDimitry Andric (Context, getMDOrNull(Record[1 + HasTag]),
21230b57cec5SDimitry Andric getMDString(Record[2 + HasTag]),
21240b57cec5SDimitry Andric getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
21250b57cec5SDimitry Andric getDITypeRefOrNull(Record[5 + HasTag]),
2126349cc55cSDimitry Andric Record[6 + HasTag], Flags, AlignInBits, Annotations)),
21270b57cec5SDimitry Andric NextMetadataNo);
21280b57cec5SDimitry Andric NextMetadataNo++;
21290b57cec5SDimitry Andric break;
21300b57cec5SDimitry Andric }
21310b57cec5SDimitry Andric case bitc::METADATA_LABEL: {
21320b57cec5SDimitry Andric if (Record.size() != 5)
21330b57cec5SDimitry Andric return error("Invalid record");
21340b57cec5SDimitry Andric
21350b57cec5SDimitry Andric IsDistinct = Record[0] & 1;
21360b57cec5SDimitry Andric MetadataList.assignValue(
2137349cc55cSDimitry Andric GET_OR_DISTINCT(DILabel, (Context, getMDOrNull(Record[1]),
21380b57cec5SDimitry Andric getMDString(Record[2]),
21390b57cec5SDimitry Andric getMDOrNull(Record[3]), Record[4])),
21400b57cec5SDimitry Andric NextMetadataNo);
21410b57cec5SDimitry Andric NextMetadataNo++;
21420b57cec5SDimitry Andric break;
21430b57cec5SDimitry Andric }
21440b57cec5SDimitry Andric case bitc::METADATA_EXPRESSION: {
21450b57cec5SDimitry Andric if (Record.size() < 1)
21460b57cec5SDimitry Andric return error("Invalid record");
21470b57cec5SDimitry Andric
21480b57cec5SDimitry Andric IsDistinct = Record[0] & 1;
21490b57cec5SDimitry Andric uint64_t Version = Record[0] >> 1;
21500b57cec5SDimitry Andric auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
21510b57cec5SDimitry Andric
21520b57cec5SDimitry Andric SmallVector<uint64_t, 6> Buffer;
21530b57cec5SDimitry Andric if (Error Err = upgradeDIExpression(Version, Elts, Buffer))
21540b57cec5SDimitry Andric return Err;
21550b57cec5SDimitry Andric
2156349cc55cSDimitry Andric MetadataList.assignValue(GET_OR_DISTINCT(DIExpression, (Context, Elts)),
2157349cc55cSDimitry Andric NextMetadataNo);
21580b57cec5SDimitry Andric NextMetadataNo++;
21590b57cec5SDimitry Andric break;
21600b57cec5SDimitry Andric }
21610b57cec5SDimitry Andric case bitc::METADATA_GLOBAL_VAR_EXPR: {
21620b57cec5SDimitry Andric if (Record.size() != 3)
21630b57cec5SDimitry Andric return error("Invalid record");
21640b57cec5SDimitry Andric
21650b57cec5SDimitry Andric IsDistinct = Record[0];
21660b57cec5SDimitry Andric Metadata *Expr = getMDOrNull(Record[2]);
21670b57cec5SDimitry Andric if (!Expr)
21680b57cec5SDimitry Andric Expr = DIExpression::get(Context, {});
21690b57cec5SDimitry Andric MetadataList.assignValue(
21700b57cec5SDimitry Andric GET_OR_DISTINCT(DIGlobalVariableExpression,
21710b57cec5SDimitry Andric (Context, getMDOrNull(Record[1]), Expr)),
21720b57cec5SDimitry Andric NextMetadataNo);
21730b57cec5SDimitry Andric NextMetadataNo++;
21740b57cec5SDimitry Andric break;
21750b57cec5SDimitry Andric }
21760b57cec5SDimitry Andric case bitc::METADATA_OBJC_PROPERTY: {
21770b57cec5SDimitry Andric if (Record.size() != 8)
21780b57cec5SDimitry Andric return error("Invalid record");
21790b57cec5SDimitry Andric
21800b57cec5SDimitry Andric IsDistinct = Record[0];
21810b57cec5SDimitry Andric MetadataList.assignValue(
21820b57cec5SDimitry Andric GET_OR_DISTINCT(DIObjCProperty,
21830b57cec5SDimitry Andric (Context, getMDString(Record[1]),
21840b57cec5SDimitry Andric getMDOrNull(Record[2]), Record[3],
21850b57cec5SDimitry Andric getMDString(Record[4]), getMDString(Record[5]),
21860b57cec5SDimitry Andric Record[6], getDITypeRefOrNull(Record[7]))),
21870b57cec5SDimitry Andric NextMetadataNo);
21880b57cec5SDimitry Andric NextMetadataNo++;
21890b57cec5SDimitry Andric break;
21900b57cec5SDimitry Andric }
21910b57cec5SDimitry Andric case bitc::METADATA_IMPORTED_ENTITY: {
219281ad6265SDimitry Andric if (Record.size() < 6 || Record.size() > 8)
219381ad6265SDimitry Andric return error("Invalid DIImportedEntity record");
21940b57cec5SDimitry Andric
21950b57cec5SDimitry Andric IsDistinct = Record[0];
2196349cc55cSDimitry Andric bool HasFile = (Record.size() >= 7);
2197349cc55cSDimitry Andric bool HasElements = (Record.size() >= 8);
21980b57cec5SDimitry Andric MetadataList.assignValue(
21990b57cec5SDimitry Andric GET_OR_DISTINCT(DIImportedEntity,
22000b57cec5SDimitry Andric (Context, Record[1], getMDOrNull(Record[2]),
22010b57cec5SDimitry Andric getDITypeRefOrNull(Record[3]),
22020b57cec5SDimitry Andric HasFile ? getMDOrNull(Record[6]) : nullptr,
2203349cc55cSDimitry Andric HasFile ? Record[4] : 0, getMDString(Record[5]),
2204349cc55cSDimitry Andric HasElements ? getMDOrNull(Record[7]) : nullptr)),
22050b57cec5SDimitry Andric NextMetadataNo);
22060b57cec5SDimitry Andric NextMetadataNo++;
22070b57cec5SDimitry Andric break;
22080b57cec5SDimitry Andric }
22090b57cec5SDimitry Andric case bitc::METADATA_STRING_OLD: {
22100b57cec5SDimitry Andric std::string String(Record.begin(), Record.end());
22110b57cec5SDimitry Andric
22120b57cec5SDimitry Andric // Test for upgrading !llvm.loop.
22130b57cec5SDimitry Andric HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
22140b57cec5SDimitry Andric ++NumMDStringLoaded;
22150b57cec5SDimitry Andric Metadata *MD = MDString::get(Context, String);
22160b57cec5SDimitry Andric MetadataList.assignValue(MD, NextMetadataNo);
22170b57cec5SDimitry Andric NextMetadataNo++;
22180b57cec5SDimitry Andric break;
22190b57cec5SDimitry Andric }
22200b57cec5SDimitry Andric case bitc::METADATA_STRINGS: {
22210b57cec5SDimitry Andric auto CreateNextMDString = [&](StringRef Str) {
22220b57cec5SDimitry Andric ++NumMDStringLoaded;
22230b57cec5SDimitry Andric MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
22240b57cec5SDimitry Andric NextMetadataNo++;
22250b57cec5SDimitry Andric };
22260b57cec5SDimitry Andric if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
22270b57cec5SDimitry Andric return Err;
22280b57cec5SDimitry Andric break;
22290b57cec5SDimitry Andric }
22300b57cec5SDimitry Andric case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
22310b57cec5SDimitry Andric if (Record.size() % 2 == 0)
22320b57cec5SDimitry Andric return error("Invalid record");
22330b57cec5SDimitry Andric unsigned ValueID = Record[0];
22340b57cec5SDimitry Andric if (ValueID >= ValueList.size())
22350b57cec5SDimitry Andric return error("Invalid record");
22360b57cec5SDimitry Andric if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
22370b57cec5SDimitry Andric if (Error Err = parseGlobalObjectAttachment(
22380b57cec5SDimitry Andric *GO, ArrayRef<uint64_t>(Record).slice(1)))
22390b57cec5SDimitry Andric return Err;
22400b57cec5SDimitry Andric break;
22410b57cec5SDimitry Andric }
22420b57cec5SDimitry Andric case bitc::METADATA_KIND: {
22430b57cec5SDimitry Andric // Support older bitcode files that had METADATA_KIND records in a
22440b57cec5SDimitry Andric // block with METADATA_BLOCK_ID.
22450b57cec5SDimitry Andric if (Error Err = parseMetadataKindRecord(Record))
22460b57cec5SDimitry Andric return Err;
22470b57cec5SDimitry Andric break;
22480b57cec5SDimitry Andric }
2249fe6060f1SDimitry Andric case bitc::METADATA_ARG_LIST: {
2250fe6060f1SDimitry Andric SmallVector<ValueAsMetadata *, 4> Elts;
2251fe6060f1SDimitry Andric Elts.reserve(Record.size());
2252fe6060f1SDimitry Andric for (uint64_t Elt : Record) {
2253fe6060f1SDimitry Andric Metadata *MD = getMD(Elt);
2254fe6060f1SDimitry Andric if (isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary())
2255fe6060f1SDimitry Andric return error(
2256fe6060f1SDimitry Andric "Invalid record: DIArgList should not contain forward refs");
2257fe6060f1SDimitry Andric if (!isa<ValueAsMetadata>(MD))
2258fe6060f1SDimitry Andric return error("Invalid record");
2259fe6060f1SDimitry Andric Elts.push_back(cast<ValueAsMetadata>(MD));
2260fe6060f1SDimitry Andric }
2261fe6060f1SDimitry Andric
2262fe6060f1SDimitry Andric MetadataList.assignValue(DIArgList::get(Context, Elts), NextMetadataNo);
2263fe6060f1SDimitry Andric NextMetadataNo++;
2264fe6060f1SDimitry Andric break;
2265fe6060f1SDimitry Andric }
22660b57cec5SDimitry Andric }
22670b57cec5SDimitry Andric return Error::success();
22680b57cec5SDimitry Andric #undef GET_OR_DISTINCT
22690b57cec5SDimitry Andric }
22700b57cec5SDimitry Andric
parseMetadataStrings(ArrayRef<uint64_t> Record,StringRef Blob,function_ref<void (StringRef)> CallBack)22710b57cec5SDimitry Andric Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
22720b57cec5SDimitry Andric ArrayRef<uint64_t> Record, StringRef Blob,
22730b57cec5SDimitry Andric function_ref<void(StringRef)> CallBack) {
22740b57cec5SDimitry Andric // All the MDStrings in the block are emitted together in a single
22750b57cec5SDimitry Andric // record. The strings are concatenated and stored in a blob along with
22760b57cec5SDimitry Andric // their sizes.
22770b57cec5SDimitry Andric if (Record.size() != 2)
22780b57cec5SDimitry Andric return error("Invalid record: metadata strings layout");
22790b57cec5SDimitry Andric
22800b57cec5SDimitry Andric unsigned NumStrings = Record[0];
22810b57cec5SDimitry Andric unsigned StringsOffset = Record[1];
22820b57cec5SDimitry Andric if (!NumStrings)
22830b57cec5SDimitry Andric return error("Invalid record: metadata strings with no strings");
22840b57cec5SDimitry Andric if (StringsOffset > Blob.size())
22850b57cec5SDimitry Andric return error("Invalid record: metadata strings corrupt offset");
22860b57cec5SDimitry Andric
22870b57cec5SDimitry Andric StringRef Lengths = Blob.slice(0, StringsOffset);
22880b57cec5SDimitry Andric SimpleBitstreamCursor R(Lengths);
22890b57cec5SDimitry Andric
22900b57cec5SDimitry Andric StringRef Strings = Blob.drop_front(StringsOffset);
22910b57cec5SDimitry Andric do {
22920b57cec5SDimitry Andric if (R.AtEndOfStream())
22930b57cec5SDimitry Andric return error("Invalid record: metadata strings bad length");
22940b57cec5SDimitry Andric
2295349cc55cSDimitry Andric uint32_t Size;
2296349cc55cSDimitry Andric if (Error E = R.ReadVBR(6).moveInto(Size))
2297349cc55cSDimitry Andric return E;
22980b57cec5SDimitry Andric if (Strings.size() < Size)
22990b57cec5SDimitry Andric return error("Invalid record: metadata strings truncated chars");
23000b57cec5SDimitry Andric
23010b57cec5SDimitry Andric CallBack(Strings.slice(0, Size));
23020b57cec5SDimitry Andric Strings = Strings.drop_front(Size);
23030b57cec5SDimitry Andric } while (--NumStrings);
23040b57cec5SDimitry Andric
23050b57cec5SDimitry Andric return Error::success();
23060b57cec5SDimitry Andric }
23070b57cec5SDimitry Andric
parseGlobalObjectAttachment(GlobalObject & GO,ArrayRef<uint64_t> Record)23080b57cec5SDimitry Andric Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
23090b57cec5SDimitry Andric GlobalObject &GO, ArrayRef<uint64_t> Record) {
23100b57cec5SDimitry Andric assert(Record.size() % 2 == 0);
23110b57cec5SDimitry Andric for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
23120b57cec5SDimitry Andric auto K = MDKindMap.find(Record[I]);
23130b57cec5SDimitry Andric if (K == MDKindMap.end())
23140b57cec5SDimitry Andric return error("Invalid ID");
2315e8d8bef9SDimitry Andric MDNode *MD =
2316e8d8bef9SDimitry Andric dyn_cast_or_null<MDNode>(getMetadataFwdRefOrLoad(Record[I + 1]));
23170b57cec5SDimitry Andric if (!MD)
23180b57cec5SDimitry Andric return error("Invalid metadata attachment: expect fwd ref to MDNode");
23190b57cec5SDimitry Andric GO.addMetadata(K->second, *MD);
23200b57cec5SDimitry Andric }
23210b57cec5SDimitry Andric return Error::success();
23220b57cec5SDimitry Andric }
23230b57cec5SDimitry Andric
23240b57cec5SDimitry Andric /// Parse metadata attachments.
parseMetadataAttachment(Function & F,ArrayRef<Instruction * > InstructionList)23250b57cec5SDimitry Andric Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
232681ad6265SDimitry Andric Function &F, ArrayRef<Instruction *> InstructionList) {
23270b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
23280b57cec5SDimitry Andric return Err;
23290b57cec5SDimitry Andric
23300b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record;
23310b57cec5SDimitry Andric PlaceholderQueue Placeholders;
23320b57cec5SDimitry Andric
23330b57cec5SDimitry Andric while (true) {
2334349cc55cSDimitry Andric BitstreamEntry Entry;
2335349cc55cSDimitry Andric if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2336349cc55cSDimitry Andric return E;
23370b57cec5SDimitry Andric
23380b57cec5SDimitry Andric switch (Entry.Kind) {
23390b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
23400b57cec5SDimitry Andric case BitstreamEntry::Error:
23410b57cec5SDimitry Andric return error("Malformed block");
23420b57cec5SDimitry Andric case BitstreamEntry::EndBlock:
23430b57cec5SDimitry Andric resolveForwardRefsAndPlaceholders(Placeholders);
23440b57cec5SDimitry Andric return Error::success();
23450b57cec5SDimitry Andric case BitstreamEntry::Record:
23460b57cec5SDimitry Andric // The interesting case.
23470b57cec5SDimitry Andric break;
23480b57cec5SDimitry Andric }
23490b57cec5SDimitry Andric
23500b57cec5SDimitry Andric // Read a metadata attachment record.
23510b57cec5SDimitry Andric Record.clear();
23520b57cec5SDimitry Andric ++NumMDRecordLoaded;
23530b57cec5SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
23540b57cec5SDimitry Andric if (!MaybeRecord)
23550b57cec5SDimitry Andric return MaybeRecord.takeError();
23560b57cec5SDimitry Andric switch (MaybeRecord.get()) {
23570b57cec5SDimitry Andric default: // Default behavior: ignore.
23580b57cec5SDimitry Andric break;
23590b57cec5SDimitry Andric case bitc::METADATA_ATTACHMENT: {
23600b57cec5SDimitry Andric unsigned RecordLength = Record.size();
23610b57cec5SDimitry Andric if (Record.empty())
23620b57cec5SDimitry Andric return error("Invalid record");
23630b57cec5SDimitry Andric if (RecordLength % 2 == 0) {
23640b57cec5SDimitry Andric // A function attachment.
23650b57cec5SDimitry Andric if (Error Err = parseGlobalObjectAttachment(F, Record))
23660b57cec5SDimitry Andric return Err;
23670b57cec5SDimitry Andric continue;
23680b57cec5SDimitry Andric }
23690b57cec5SDimitry Andric
23700b57cec5SDimitry Andric // An instruction attachment.
23710b57cec5SDimitry Andric Instruction *Inst = InstructionList[Record[0]];
23720b57cec5SDimitry Andric for (unsigned i = 1; i != RecordLength; i = i + 2) {
23730b57cec5SDimitry Andric unsigned Kind = Record[i];
23740b57cec5SDimitry Andric DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
23750b57cec5SDimitry Andric if (I == MDKindMap.end())
23760b57cec5SDimitry Andric return error("Invalid ID");
23770b57cec5SDimitry Andric if (I->second == LLVMContext::MD_tbaa && StripTBAA)
23780b57cec5SDimitry Andric continue;
23790b57cec5SDimitry Andric
23800b57cec5SDimitry Andric auto Idx = Record[i + 1];
23810b57cec5SDimitry Andric if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
23820b57cec5SDimitry Andric !MetadataList.lookup(Idx)) {
23830b57cec5SDimitry Andric // Load the attachment if it is in the lazy-loadable range and hasn't
23840b57cec5SDimitry Andric // been loaded yet.
23850b57cec5SDimitry Andric lazyLoadOneMetadata(Idx, Placeholders);
23860b57cec5SDimitry Andric resolveForwardRefsAndPlaceholders(Placeholders);
23870b57cec5SDimitry Andric }
23880b57cec5SDimitry Andric
23890b57cec5SDimitry Andric Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
23900b57cec5SDimitry Andric if (isa<LocalAsMetadata>(Node))
23910b57cec5SDimitry Andric // Drop the attachment. This used to be legal, but there's no
23920b57cec5SDimitry Andric // upgrade path.
23930b57cec5SDimitry Andric break;
23940b57cec5SDimitry Andric MDNode *MD = dyn_cast_or_null<MDNode>(Node);
23950b57cec5SDimitry Andric if (!MD)
23960b57cec5SDimitry Andric return error("Invalid metadata attachment");
23970b57cec5SDimitry Andric
23980b57cec5SDimitry Andric if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
23990b57cec5SDimitry Andric MD = upgradeInstructionLoopAttachment(*MD);
24000b57cec5SDimitry Andric
24010b57cec5SDimitry Andric if (I->second == LLVMContext::MD_tbaa) {
24020b57cec5SDimitry Andric assert(!MD->isTemporary() && "should load MDs before attachments");
24030b57cec5SDimitry Andric MD = UpgradeTBAANode(*MD);
24040b57cec5SDimitry Andric }
24050b57cec5SDimitry Andric Inst->setMetadata(I->second, MD);
24060b57cec5SDimitry Andric }
24070b57cec5SDimitry Andric break;
24080b57cec5SDimitry Andric }
24090b57cec5SDimitry Andric }
24100b57cec5SDimitry Andric }
24110b57cec5SDimitry Andric }
24120b57cec5SDimitry Andric
24130b57cec5SDimitry Andric /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
parseMetadataKindRecord(SmallVectorImpl<uint64_t> & Record)24140b57cec5SDimitry Andric Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
24150b57cec5SDimitry Andric SmallVectorImpl<uint64_t> &Record) {
24160b57cec5SDimitry Andric if (Record.size() < 2)
24170b57cec5SDimitry Andric return error("Invalid record");
24180b57cec5SDimitry Andric
24190b57cec5SDimitry Andric unsigned Kind = Record[0];
24200b57cec5SDimitry Andric SmallString<8> Name(Record.begin() + 1, Record.end());
24210b57cec5SDimitry Andric
24220b57cec5SDimitry Andric unsigned NewKind = TheModule.getMDKindID(Name.str());
24230b57cec5SDimitry Andric if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
24240b57cec5SDimitry Andric return error("Conflicting METADATA_KIND records");
24250b57cec5SDimitry Andric return Error::success();
24260b57cec5SDimitry Andric }
24270b57cec5SDimitry Andric
24280b57cec5SDimitry Andric /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
parseMetadataKinds()24290b57cec5SDimitry Andric Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
24300b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
24310b57cec5SDimitry Andric return Err;
24320b57cec5SDimitry Andric
24330b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record;
24340b57cec5SDimitry Andric
24350b57cec5SDimitry Andric // Read all the records.
24360b57cec5SDimitry Andric while (true) {
2437349cc55cSDimitry Andric BitstreamEntry Entry;
2438349cc55cSDimitry Andric if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2439349cc55cSDimitry Andric return E;
24400b57cec5SDimitry Andric
24410b57cec5SDimitry Andric switch (Entry.Kind) {
24420b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
24430b57cec5SDimitry Andric case BitstreamEntry::Error:
24440b57cec5SDimitry Andric return error("Malformed block");
24450b57cec5SDimitry Andric case BitstreamEntry::EndBlock:
24460b57cec5SDimitry Andric return Error::success();
24470b57cec5SDimitry Andric case BitstreamEntry::Record:
24480b57cec5SDimitry Andric // The interesting case.
24490b57cec5SDimitry Andric break;
24500b57cec5SDimitry Andric }
24510b57cec5SDimitry Andric
24520b57cec5SDimitry Andric // Read a record.
24530b57cec5SDimitry Andric Record.clear();
24540b57cec5SDimitry Andric ++NumMDRecordLoaded;
24550b57cec5SDimitry Andric Expected<unsigned> MaybeCode = Stream.readRecord(Entry.ID, Record);
24560b57cec5SDimitry Andric if (!MaybeCode)
24570b57cec5SDimitry Andric return MaybeCode.takeError();
24580b57cec5SDimitry Andric switch (MaybeCode.get()) {
24590b57cec5SDimitry Andric default: // Default behavior: ignore.
24600b57cec5SDimitry Andric break;
24610b57cec5SDimitry Andric case bitc::METADATA_KIND: {
24620b57cec5SDimitry Andric if (Error Err = parseMetadataKindRecord(Record))
24630b57cec5SDimitry Andric return Err;
24640b57cec5SDimitry Andric break;
24650b57cec5SDimitry Andric }
24660b57cec5SDimitry Andric }
24670b57cec5SDimitry Andric }
24680b57cec5SDimitry Andric }
24690b57cec5SDimitry Andric
operator =(MetadataLoader && RHS)24700b57cec5SDimitry Andric MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
24710b57cec5SDimitry Andric Pimpl = std::move(RHS.Pimpl);
24720b57cec5SDimitry Andric return *this;
24730b57cec5SDimitry Andric }
MetadataLoader(MetadataLoader && RHS)24740b57cec5SDimitry Andric MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
24750b57cec5SDimitry Andric : Pimpl(std::move(RHS.Pimpl)) {}
24760b57cec5SDimitry Andric
24770b57cec5SDimitry Andric MetadataLoader::~MetadataLoader() = default;
MetadataLoader(BitstreamCursor & Stream,Module & TheModule,BitcodeReaderValueList & ValueList,bool IsImporting,MetadataLoaderCallbacks Callbacks)24780b57cec5SDimitry Andric MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
24790b57cec5SDimitry Andric BitcodeReaderValueList &ValueList,
24800b57cec5SDimitry Andric bool IsImporting,
2481bdd1243dSDimitry Andric MetadataLoaderCallbacks Callbacks)
24828bcb0991SDimitry Andric : Pimpl(std::make_unique<MetadataLoaderImpl>(
2483bdd1243dSDimitry Andric Stream, TheModule, ValueList, std::move(Callbacks), IsImporting)) {}
24840b57cec5SDimitry Andric
parseMetadata(bool ModuleLevel)24850b57cec5SDimitry Andric Error MetadataLoader::parseMetadata(bool ModuleLevel) {
24860b57cec5SDimitry Andric return Pimpl->parseMetadata(ModuleLevel);
24870b57cec5SDimitry Andric }
24880b57cec5SDimitry Andric
hasFwdRefs() const24890b57cec5SDimitry Andric bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
24900b57cec5SDimitry Andric
24910b57cec5SDimitry Andric /// Return the given metadata, creating a replaceable forward reference if
24920b57cec5SDimitry Andric /// necessary.
getMetadataFwdRefOrLoad(unsigned Idx)24930b57cec5SDimitry Andric Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
24940b57cec5SDimitry Andric return Pimpl->getMetadataFwdRefOrLoad(Idx);
24950b57cec5SDimitry Andric }
24960b57cec5SDimitry Andric
lookupSubprogramForFunction(Function * F)24970b57cec5SDimitry Andric DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
24980b57cec5SDimitry Andric return Pimpl->lookupSubprogramForFunction(F);
24990b57cec5SDimitry Andric }
25000b57cec5SDimitry Andric
parseMetadataAttachment(Function & F,ArrayRef<Instruction * > InstructionList)25010b57cec5SDimitry Andric Error MetadataLoader::parseMetadataAttachment(
250281ad6265SDimitry Andric Function &F, ArrayRef<Instruction *> InstructionList) {
25030b57cec5SDimitry Andric return Pimpl->parseMetadataAttachment(F, InstructionList);
25040b57cec5SDimitry Andric }
25050b57cec5SDimitry Andric
parseMetadataKinds()25060b57cec5SDimitry Andric Error MetadataLoader::parseMetadataKinds() {
25070b57cec5SDimitry Andric return Pimpl->parseMetadataKinds();
25080b57cec5SDimitry Andric }
25090b57cec5SDimitry Andric
setStripTBAA(bool StripTBAA)25100b57cec5SDimitry Andric void MetadataLoader::setStripTBAA(bool StripTBAA) {
25110b57cec5SDimitry Andric return Pimpl->setStripTBAA(StripTBAA);
25120b57cec5SDimitry Andric }
25130b57cec5SDimitry Andric
isStrippingTBAA()25140b57cec5SDimitry Andric bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
25150b57cec5SDimitry Andric
size() const25160b57cec5SDimitry Andric unsigned MetadataLoader::size() const { return Pimpl->size(); }
shrinkTo(unsigned N)25170b57cec5SDimitry Andric void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
25180b57cec5SDimitry Andric
upgradeDebugIntrinsics(Function & F)25190b57cec5SDimitry Andric void MetadataLoader::upgradeDebugIntrinsics(Function &F) {
25200b57cec5SDimitry Andric return Pimpl->upgradeDebugIntrinsics(F);
25210b57cec5SDimitry Andric }
2522