IR: Split Metadata from Value

Split `Metadata` away from the `Value` class hierarchy, as part of
PR21532.  Assembly and bitcode changes are in the wings, but this is the
bulk of the change for the IR C++ API.

I have a follow-up patch prepared for `clang`.  If this breaks other
sub-projects, I apologize in advance :(.  Help me compile it on Darwin
I'll try to fix it.  FWIW, the errors should be easy to fix, so it may
be simpler to just fix it yourself.

This breaks the build for all metadata-related code that's out-of-tree.
Rest assured the transition is mechanical and the compiler should catch
almost all of the problems.

Here's a quick guide for updating your code:

  - `Metadata` is the root of a class hierarchy with three main classes:
    `MDNode`, `MDString`, and `ValueAsMetadata`.  It is distinct from
    the `Value` class hierarchy.  It is typeless -- i.e., instances do
    *not* have a `Type`.

  - `MDNode`'s operands are all `Metadata *` (instead of `Value *`).

  - `TrackingVH<MDNode>` and `WeakVH` referring to metadata can be
    replaced with `TrackingMDNodeRef` and `TrackingMDRef`, respectively.

    If you're referring solely to resolved `MDNode`s -- post graph
    construction -- just use `MDNode*`.

  - `MDNode` (and the rest of `Metadata`) have only limited support for
    `replaceAllUsesWith()`.

    As long as an `MDNode` is pointing at a forward declaration -- the
    result of `MDNode::getTemporary()` -- it maintains a side map of its
    uses and can RAUW itself.  Once the forward declarations are fully
    resolved RAUW support is dropped on the ground.  This means that
    uniquing collisions on changing operands cause nodes to become
    "distinct".  (This already happened fairly commonly, whenever an
    operand went to null.)

    If you're constructing complex (non self-reference) `MDNode` cycles,
    you need to call `MDNode::resolveCycles()` on each node (or on a
    top-level node that somehow references all of the nodes).  Also,
    don't do that.  Metadata cycles (and the RAUW machinery needed to
    construct them) are expensive.

  - An `MDNode` can only refer to a `Constant` through a bridge called
    `ConstantAsMetadata` (one of the subclasses of `ValueAsMetadata`).

    As a side effect, accessing an operand of an `MDNode` that is known
    to be, e.g., `ConstantInt`, takes three steps: first, cast from
    `Metadata` to `ConstantAsMetadata`; second, extract the `Constant`;
    third, cast down to `ConstantInt`.

    The eventual goal is to introduce `MDInt`/`MDFloat`/etc. and have
    metadata schema owners transition away from using `Constant`s when
    the type isn't important (and they don't care about referring to
    `GlobalValue`s).

    In the meantime, I've added transitional API to the `mdconst`
    namespace that matches semantics with the old code, in order to
    avoid adding the error-prone three-step equivalent to every call
    site.  If your old code was:

        MDNode *N = foo();
        bar(isa             <ConstantInt>(N->getOperand(0)));
        baz(cast            <ConstantInt>(N->getOperand(1)));
        bak(cast_or_null    <ConstantInt>(N->getOperand(2)));
        bat(dyn_cast        <ConstantInt>(N->getOperand(3)));
        bay(dyn_cast_or_null<ConstantInt>(N->getOperand(4)));

    you can trivially match its semantics with:

        MDNode *N = foo();
        bar(mdconst::hasa               <ConstantInt>(N->getOperand(0)));
        baz(mdconst::extract            <ConstantInt>(N->getOperand(1)));
        bak(mdconst::extract_or_null    <ConstantInt>(N->getOperand(2)));
        bat(mdconst::dyn_extract        <ConstantInt>(N->getOperand(3)));
        bay(mdconst::dyn_extract_or_null<ConstantInt>(N->getOperand(4)));

    and when you transition your metadata schema to `MDInt`:

        MDNode *N = foo();
        bar(isa             <MDInt>(N->getOperand(0)));
        baz(cast            <MDInt>(N->getOperand(1)));
        bak(cast_or_null    <MDInt>(N->getOperand(2)));
        bat(dyn_cast        <MDInt>(N->getOperand(3)));
        bay(dyn_cast_or_null<MDInt>(N->getOperand(4)));

  - A `CallInst` -- specifically, intrinsic instructions -- can refer to
    metadata through a bridge called `MetadataAsValue`.  This is a
    subclass of `Value` where `getType()->isMetadataTy()`.

    `MetadataAsValue` is the *only* class that can legally refer to a
    `LocalAsMetadata`, which is a bridged form of non-`Constant` values
    like `Argument` and `Instruction`.  It can also refer to any other
    `Metadata` subclass.

(I'll break all your testcases in a follow-up commit, when I propagate
this change to assembly.)

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@223802 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Duncan P. N. Exon Smith
2014-12-09 18:38:53 +00:00
parent db7b69e3a6
commit dad20b2ae2
88 changed files with 3370 additions and 1970 deletions

View File

@ -17,67 +17,29 @@ using namespace llvm;
// DebugLoc Implementation
//===----------------------------------------------------------------------===//
MDNode *DebugLoc::getScope(const LLVMContext &Ctx) const {
if (ScopeIdx == 0) return nullptr;
if (ScopeIdx > 0) {
// Positive ScopeIdx is an index into ScopeRecords, which has no inlined-at
// position specified.
assert(unsigned(ScopeIdx) <= Ctx.pImpl->ScopeRecords.size() &&
"Invalid ScopeIdx!");
return Ctx.pImpl->ScopeRecords[ScopeIdx-1].get();
}
// Otherwise, the index is in the ScopeInlinedAtRecords array.
assert(unsigned(-ScopeIdx) <= Ctx.pImpl->ScopeInlinedAtRecords.size() &&
"Invalid ScopeIdx");
return Ctx.pImpl->ScopeInlinedAtRecords[-ScopeIdx-1].first.get();
}
unsigned DebugLoc::getLine() const { return DILocation(Loc).getLineNumber(); }
unsigned DebugLoc::getCol() const { return DILocation(Loc).getColumnNumber(); }
MDNode *DebugLoc::getInlinedAt(const LLVMContext &Ctx) const {
// Positive ScopeIdx is an index into ScopeRecords, which has no inlined-at
// position specified. Zero is invalid.
if (ScopeIdx >= 0) return nullptr;
// Otherwise, the index is in the ScopeInlinedAtRecords array.
assert(unsigned(-ScopeIdx) <= Ctx.pImpl->ScopeInlinedAtRecords.size() &&
"Invalid ScopeIdx");
return Ctx.pImpl->ScopeInlinedAtRecords[-ScopeIdx-1].second.get();
MDNode *DebugLoc::getScope() const { return DILocation(Loc).getScope(); }
MDNode *DebugLoc::getInlinedAt() const {
return DILocation(Loc).getOrigLocation();
}
/// Return both the Scope and the InlinedAt values.
void DebugLoc::getScopeAndInlinedAt(MDNode *&Scope, MDNode *&IA,
const LLVMContext &Ctx) const {
if (ScopeIdx == 0) {
Scope = IA = nullptr;
return;
}
if (ScopeIdx > 0) {
// Positive ScopeIdx is an index into ScopeRecords, which has no inlined-at
// position specified.
assert(unsigned(ScopeIdx) <= Ctx.pImpl->ScopeRecords.size() &&
"Invalid ScopeIdx!");
Scope = Ctx.pImpl->ScopeRecords[ScopeIdx-1].get();
IA = nullptr;
return;
}
// Otherwise, the index is in the ScopeInlinedAtRecords array.
assert(unsigned(-ScopeIdx) <= Ctx.pImpl->ScopeInlinedAtRecords.size() &&
"Invalid ScopeIdx");
Scope = Ctx.pImpl->ScopeInlinedAtRecords[-ScopeIdx-1].first.get();
IA = Ctx.pImpl->ScopeInlinedAtRecords[-ScopeIdx-1].second.get();
void DebugLoc::getScopeAndInlinedAt(MDNode *&Scope, MDNode *&IA) const {
Scope = getScope();
IA = getInlinedAt();
}
MDNode *DebugLoc::getScopeNode(const LLVMContext &Ctx) const {
if (MDNode *InlinedAt = getInlinedAt(Ctx))
return DebugLoc::getFromDILocation(InlinedAt).getScopeNode(Ctx);
return getScope(Ctx);
MDNode *DebugLoc::getScopeNode() const {
if (MDNode *InlinedAt = getInlinedAt())
return DebugLoc::getFromDILocation(InlinedAt).getScopeNode();
return getScope();
}
DebugLoc DebugLoc::getFnDebugLoc(const LLVMContext &Ctx) const {
const MDNode *Scope = getScopeNode(Ctx);
DebugLoc DebugLoc::getFnDebugLoc() const {
const MDNode *Scope = getScopeNode();
DISubprogram SP = getDISubprogram(Scope);
if (SP.isSubprogram())
return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
@ -87,53 +49,32 @@ DebugLoc DebugLoc::getFnDebugLoc(const LLVMContext &Ctx) const {
DebugLoc DebugLoc::get(unsigned Line, unsigned Col,
MDNode *Scope, MDNode *InlinedAt) {
DebugLoc Result;
// If no scope is available, this is an unknown location.
if (!Scope) return Result;
if (!Scope)
return DebugLoc();
// Saturate line and col to "unknown".
// FIXME: Allow 16-bits for columns.
if (Col > 255) Col = 0;
if (Line >= (1 << 24)) Line = 0;
Result.LineCol = Line | (Col << 24);
LLVMContext &Ctx = Scope->getContext();
// If there is no inlined-at location, use the ScopeRecords array.
if (!InlinedAt)
Result.ScopeIdx = Ctx.pImpl->getOrAddScopeRecordIdxEntry(Scope, 0);
else
Result.ScopeIdx = Ctx.pImpl->getOrAddScopeInlinedAtIdxEntry(Scope,
InlinedAt, 0);
return Result;
LLVMContext &Context = Scope->getContext();
Type *Int32 = Type::getInt32Ty(Context);
Metadata *Elts[] = {ConstantAsMetadata::get(ConstantInt::get(Int32, Line)),
ConstantAsMetadata::get(ConstantInt::get(Int32, Col)),
Scope, InlinedAt};
return getFromDILocation(MDNode::get(Context, Elts));
}
/// getAsMDNode - This method converts the compressed DebugLoc node into a
/// DILocation-compatible MDNode.
MDNode *DebugLoc::getAsMDNode(const LLVMContext &Ctx) const {
if (isUnknown()) return nullptr;
MDNode *Scope, *IA;
getScopeAndInlinedAt(Scope, IA, Ctx);
assert(Scope && "If scope is null, this should be isUnknown()");
LLVMContext &Ctx2 = Scope->getContext();
Type *Int32 = Type::getInt32Ty(Ctx2);
Value *Elts[] = {
ConstantInt::get(Int32, getLine()), ConstantInt::get(Int32, getCol()),
Scope, IA
};
return MDNode::get(Ctx2, Elts);
}
MDNode *DebugLoc::getAsMDNode() const { return Loc; }
/// getFromDILocation - Translate the DILocation quad into a DebugLoc.
DebugLoc DebugLoc::getFromDILocation(MDNode *N) {
DILocation Loc(N);
MDNode *Scope = Loc.getScope();
if (!Scope) return DebugLoc();
return get(Loc.getLineNumber(), Loc.getColumnNumber(), Scope,
Loc.getOrigLocation());
DebugLoc Loc;
Loc.Loc.reset(N);
return Loc;
}
/// getFromDILexicalBlock - Translate the DILexicalBlock into a DebugLoc.
@ -145,26 +86,26 @@ DebugLoc DebugLoc::getFromDILexicalBlock(MDNode *N) {
nullptr);
}
void DebugLoc::dump(const LLVMContext &Ctx) const {
void DebugLoc::dump() const {
#ifndef NDEBUG
if (!isUnknown()) {
dbgs() << getLine();
if (getCol() != 0)
dbgs() << ',' << getCol();
DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(getInlinedAt(Ctx));
DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(getInlinedAt());
if (!InlinedAtDL.isUnknown()) {
dbgs() << " @ ";
InlinedAtDL.dump(Ctx);
InlinedAtDL.dump();
} else
dbgs() << "\n";
}
#endif
}
void DebugLoc::print(const LLVMContext &Ctx, raw_ostream &OS) const {
void DebugLoc::print(raw_ostream &OS) const {
if (!isUnknown()) {
// Print source line info.
DIScope Scope(getScope(Ctx));
DIScope Scope(getScope());
assert((!Scope || Scope.isScope()) &&
"Scope of a DebugLoc should be null or a DIScope.");
if (Scope)
@ -174,179 +115,11 @@ void DebugLoc::print(const LLVMContext &Ctx, raw_ostream &OS) const {
OS << ':' << getLine();
if (getCol() != 0)
OS << ':' << getCol();
DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(getInlinedAt(Ctx));
DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(getInlinedAt());
if (!InlinedAtDL.isUnknown()) {
OS << " @[ ";
InlinedAtDL.print(Ctx, OS);
InlinedAtDL.print(OS);
OS << " ]";
}
}
}
//===----------------------------------------------------------------------===//
// DenseMap specialization
//===----------------------------------------------------------------------===//
unsigned DenseMapInfo<DebugLoc>::getHashValue(const DebugLoc &Key) {
return static_cast<unsigned>(hash_combine(Key.LineCol, Key.ScopeIdx));
}
//===----------------------------------------------------------------------===//
// LLVMContextImpl Implementation
//===----------------------------------------------------------------------===//
int LLVMContextImpl::getOrAddScopeRecordIdxEntry(MDNode *Scope,
int ExistingIdx) {
// If we already have an entry for this scope, return it.
int &Idx = ScopeRecordIdx[Scope];
if (Idx) return Idx;
// If we don't have an entry, but ExistingIdx is specified, use it.
if (ExistingIdx)
return Idx = ExistingIdx;
// Otherwise add a new entry.
// Start out ScopeRecords with a minimal reasonable size to avoid
// excessive reallocation starting out.
if (ScopeRecords.empty())
ScopeRecords.reserve(128);
// Index is biased by 1 for index.
Idx = ScopeRecords.size()+1;
ScopeRecords.push_back(DebugRecVH(Scope, this, Idx));
return Idx;
}
int LLVMContextImpl::getOrAddScopeInlinedAtIdxEntry(MDNode *Scope, MDNode *IA,
int ExistingIdx) {
// If we already have an entry, return it.
int &Idx = ScopeInlinedAtIdx[std::make_pair(Scope, IA)];
if (Idx) return Idx;
// If we don't have an entry, but ExistingIdx is specified, use it.
if (ExistingIdx)
return Idx = ExistingIdx;
// Start out ScopeInlinedAtRecords with a minimal reasonable size to avoid
// excessive reallocation starting out.
if (ScopeInlinedAtRecords.empty())
ScopeInlinedAtRecords.reserve(128);
// Index is biased by 1 and negated.
Idx = -ScopeInlinedAtRecords.size()-1;
ScopeInlinedAtRecords.push_back(std::make_pair(DebugRecVH(Scope, this, Idx),
DebugRecVH(IA, this, Idx)));
return Idx;
}
//===----------------------------------------------------------------------===//
// DebugRecVH Implementation
//===----------------------------------------------------------------------===//
/// deleted - The MDNode this is pointing to got deleted, so this pointer needs
/// to drop to null and we need remove our entry from the DenseMap.
void DebugRecVH::deleted() {
// If this is a non-canonical reference, just drop the value to null, we know
// it doesn't have a map entry.
if (Idx == 0) {
setValPtr(nullptr);
return;
}
MDNode *Cur = get();
// If the index is positive, it is an entry in ScopeRecords.
if (Idx > 0) {
assert(Ctx->ScopeRecordIdx[Cur] == Idx && "Mapping out of date!");
Ctx->ScopeRecordIdx.erase(Cur);
// Reset this VH to null and we're done.
setValPtr(nullptr);
Idx = 0;
return;
}
// Otherwise, it is an entry in ScopeInlinedAtRecords, we don't know if it
// is the scope or the inlined-at record entry.
assert(unsigned(-Idx-1) < Ctx->ScopeInlinedAtRecords.size());
std::pair<DebugRecVH, DebugRecVH> &Entry = Ctx->ScopeInlinedAtRecords[-Idx-1];
assert((this == &Entry.first || this == &Entry.second) &&
"Mapping out of date!");
MDNode *OldScope = Entry.first.get();
MDNode *OldInlinedAt = Entry.second.get();
assert(OldScope && OldInlinedAt &&
"Entry should be non-canonical if either val dropped to null");
// Otherwise, we do have an entry in it, nuke it and we're done.
assert(Ctx->ScopeInlinedAtIdx[std::make_pair(OldScope, OldInlinedAt)] == Idx&&
"Mapping out of date");
Ctx->ScopeInlinedAtIdx.erase(std::make_pair(OldScope, OldInlinedAt));
// Reset this VH to null. Drop both 'Idx' values to null to indicate that
// we're in non-canonical form now.
setValPtr(nullptr);
Entry.first.Idx = Entry.second.Idx = 0;
}
void DebugRecVH::allUsesReplacedWith(Value *NewVa) {
// If being replaced with a non-mdnode value (e.g. undef) handle this as if
// the mdnode got deleted.
MDNode *NewVal = dyn_cast<MDNode>(NewVa);
if (!NewVal) return deleted();
// If this is a non-canonical reference, just change it, we know it already
// doesn't have a map entry.
if (Idx == 0) {
setValPtr(NewVa);
return;
}
MDNode *OldVal = get();
assert(OldVal != NewVa && "Node replaced with self?");
// If the index is positive, it is an entry in ScopeRecords.
if (Idx > 0) {
assert(Ctx->ScopeRecordIdx[OldVal] == Idx && "Mapping out of date!");
Ctx->ScopeRecordIdx.erase(OldVal);
setValPtr(NewVal);
int NewEntry = Ctx->getOrAddScopeRecordIdxEntry(NewVal, Idx);
// If NewVal already has an entry, this becomes a non-canonical reference,
// just drop Idx to 0 to signify this.
if (NewEntry != Idx)
Idx = 0;
return;
}
// Otherwise, it is an entry in ScopeInlinedAtRecords, we don't know if it
// is the scope or the inlined-at record entry.
assert(unsigned(-Idx-1) < Ctx->ScopeInlinedAtRecords.size());
std::pair<DebugRecVH, DebugRecVH> &Entry = Ctx->ScopeInlinedAtRecords[-Idx-1];
assert((this == &Entry.first || this == &Entry.second) &&
"Mapping out of date!");
MDNode *OldScope = Entry.first.get();
MDNode *OldInlinedAt = Entry.second.get();
assert(OldScope && OldInlinedAt &&
"Entry should be non-canonical if either val dropped to null");
// Otherwise, we do have an entry in it, nuke it and we're done.
assert(Ctx->ScopeInlinedAtIdx[std::make_pair(OldScope, OldInlinedAt)] == Idx&&
"Mapping out of date");
Ctx->ScopeInlinedAtIdx.erase(std::make_pair(OldScope, OldInlinedAt));
// Reset this VH to the new value.
setValPtr(NewVal);
int NewIdx = Ctx->getOrAddScopeInlinedAtIdxEntry(Entry.first.get(),
Entry.second.get(), Idx);
// If NewVal already has an entry, this becomes a non-canonical reference,
// just drop Idx to 0 to signify this.
if (NewIdx != Idx) {
std::pair<DebugRecVH, DebugRecVH> &Entry=Ctx->ScopeInlinedAtRecords[-Idx-1];
Entry.first.Idx = Entry.second.Idx = 0;
}
}