llvm.org GIT mirror llvm / dad20b2
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 Duncan P. N. Exon Smith 5 years ago
88 changed file(s) with 3440 addition(s) and 2040 deletion(s). Raw diff Collapse all Expand all
1717
1818 using namespace llvm;
1919
20 static Metadata *unwrapMetadata(LLVMValueRef VRef) {
21 Value *V = unwrap(VRef);
22 if (!V)
23 return nullptr;
24 if (auto *MD = dyn_cast(V))
25 return MD->getMetadata();
26 return ValueAsMetadata::get(V);
27 }
28
29 static SmallVector unwrapMetadataArray(LLVMValueRef *Data,
30 size_t Length) {
31 SmallVector Elements;
32 for (size_t I = 0; I != Length; ++I)
33 Elements.push_back(unwrapMetadata(Data[I]));
34 return Elements;
35 }
36
2037 namespace {
2138 template T unwrapDI(LLVMValueRef v) {
22 return v ? T(unwrap(v)) : T();
23 }
39 return T(cast_or_null(unwrapMetadata(v)));
40 }
41 }
42
43 static LLVMValueRef wrapDI(DIDescriptor N) {
44 return wrap(MetadataAsValue::get(N->getContext(), N));
2445 }
2546
2647 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(DIBuilder, LLVMDIBuilderRef)
4667 DIBuilder *D = unwrap(Dref);
4768 DICompileUnit CU = D->createCompileUnit(Lang, File, Dir, Producer, Optimized,
4869 Flags, RuntimeVersion);
49 return wrap(CU);
70 return wrapDI(CU);
5071 }
5172
5273 LLVMValueRef LLVMDIBuilderCreateFile(LLVMDIBuilderRef Dref, const char *File,
5374 const char *Dir) {
5475 DIBuilder *D = unwrap(Dref);
5576 DIFile F = D->createFile(File, Dir);
56 return wrap(F);
77 return wrapDI(F);
5778 }
5879
5980 LLVMValueRef LLVMDIBuilderCreateLexicalBlock(LLVMDIBuilderRef Dref,
6384 DIBuilder *D = unwrap(Dref);
6485 DILexicalBlock LB = D->createLexicalBlock(
6586 unwrapDI(Scope), unwrapDI(File), Line, Column);
66 return wrap(LB);
87 return wrapDI(LB);
6788 }
6889
6990 LLVMValueRef LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Dref,
7394 DIBuilder *D = unwrap(Dref);
7495 DILexicalBlockFile LBF = D->createLexicalBlockFile(
7596 unwrapDI(Scope), unwrapDI(File), Discriminator);
76 return wrap(LBF);
97 return wrapDI(LBF);
7798 }
7899
79100 LLVMValueRef LLVMDIBuilderCreateFunction(
86107 unwrapDI(Scope), Name, LinkageName, unwrapDI(File),
87108 Line, unwrapDI(CompositeType), IsLocalToUnit,
88109 IsDefinition, ScopeLine, Flags, IsOptimized, unwrap(Func));
89 return wrap(SP);
110 return wrapDI(SP);
90111 }
91112
92113 LLVMValueRef LLVMDIBuilderCreateLocalVariable(
97118 DIVariable V = D->createLocalVariable(
98119 Tag, unwrapDI(Scope), Name, unwrapDI(File), Line,
99120 unwrapDI(Ty), AlwaysPreserve, Flags, ArgNo);
100 return wrap(V);
121 return wrapDI(V);
101122 }
102123
103124 LLVMValueRef LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Dref,
106127 unsigned Encoding) {
107128 DIBuilder *D = unwrap(Dref);
108129 DIBasicType T = D->createBasicType(Name, SizeInBits, AlignInBits, Encoding);
109 return wrap(T);
130 return wrapDI(T);
110131 }
111132
112133 LLVMValueRef LLVMDIBuilderCreatePointerType(LLVMDIBuilderRef Dref,
117138 DIBuilder *D = unwrap(Dref);
118139 DIDerivedType T = D->createPointerType(unwrapDI(PointeeType),
119140 SizeInBits, AlignInBits, Name);
120 return wrap(T);
141 return wrapDI(T);
121142 }
122143
123144 LLVMValueRef LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Dref,
126147 DIBuilder *D = unwrap(Dref);
127148 DICompositeType CT = D->createSubroutineType(
128149 unwrapDI(File), unwrapDI(ParameterTypes));
129 return wrap(CT);
150 return wrapDI(CT);
130151 }
131152
132153 LLVMValueRef LLVMDIBuilderCreateStructType(
138159 unwrapDI(Scope), Name, unwrapDI(File), Line,
139160 SizeInBits, AlignInBits, Flags, unwrapDI(DerivedFrom),
140161 unwrapDI(ElementTypes));
141 return wrap(CT);
162 return wrapDI(CT);
142163 }
143164
144165 LLVMValueRef LLVMDIBuilderCreateMemberType(
149170 DIDerivedType DT = D->createMemberType(
150171 unwrapDI(Scope), Name, unwrapDI(File), Line,
151172 SizeInBits, AlignInBits, OffsetInBits, Flags, unwrapDI(Ty));
152 return wrap(DT);
173 return wrapDI(DT);
153174 }
154175
155176 LLVMValueRef LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Dref,
161182 DICompositeType CT =
162183 D->createArrayType(SizeInBits, AlignInBits, unwrapDI(ElementType),
163184 unwrapDI(Subscripts));
164 return wrap(CT);
185 return wrapDI(CT);
165186 }
166187
167188 LLVMValueRef LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Dref, LLVMValueRef Ty,
171192 DIDerivedType DT =
172193 D->createTypedef(unwrapDI(Ty), Name, unwrapDI(File), Line,
173194 unwrapDI(Context));
174 return wrap(DT);
195 return wrapDI(DT);
175196 }
176197
177198 LLVMValueRef LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Dref, int64_t Lo,
178199 int64_t Count) {
179200 DIBuilder *D = unwrap(Dref);
180201 DISubrange S = D->getOrCreateSubrange(Lo, Count);
181 return wrap(S);
202 return wrapDI(S);
182203 }
183204
184205 LLVMValueRef LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Dref,
185206 LLVMValueRef *Data, size_t Length) {
186207 DIBuilder *D = unwrap(Dref);
187 Value **DataValue = unwrap(Data);
188 ArrayRef Elements(DataValue, Length);
189 DIArray A = D->getOrCreateArray(Elements);
190 return wrap(A);
208 DIArray A = D->getOrCreateArray(unwrapMetadataArray(Data, Length));
209 return wrapDI(A);
191210 }
192211
193212 LLVMValueRef LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Dref,
194213 LLVMValueRef *Data,
195214 size_t Length) {
196215 DIBuilder *D = unwrap(Dref);
197 Value **DataValue = unwrap(Data);
198 ArrayRef Elements(DataValue, Length);
199 DITypeArray A = D->getOrCreateTypeArray(Elements);
200 return wrap(A);
216 DITypeArray A = D->getOrCreateTypeArray(unwrapMetadataArray(Data, Length));
217 return wrapDI(A);
201218 }
202219
203220 LLVMValueRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Dref, int64_t *Addr,
204221 size_t Length) {
205222 DIBuilder *D = unwrap(Dref);
206223 DIExpression Expr = D->createExpression(ArrayRef(Addr, Length));
207 return wrap(Expr);
224 return wrapDI(Expr);
208225 }
209226
210227 LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(LLVMDIBuilderRef Dref,
4747 LexicalScope(LexicalScope *P, const MDNode *D, const MDNode *I, bool A)
4848 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(A),
4949 LastInsn(nullptr), FirstInsn(nullptr), DFSIn(0), DFSOut(0) {
50 assert((!D || D->isResolved()) && "Expected resolved node");
51 assert((!I || I->isResolved()) && "Expected resolved node");
5052 if (Parent)
5153 Parent->addChild(this);
5254 }
115117
116118 private:
117119 LexicalScope *Parent; // Parent to this scope.
118 AssertingVH Desc; // Debug info descriptor.
119 AssertingVH InlinedAtLocation; // Location at which this
120 const MDNode *Desc; // Debug info descriptor.
121 const MDNode *InlinedAtLocation; // Location at which this
120122 // scope is inlined.
121123 bool AbstractScope; // Abstract Scope
122124 SmallVector Children; // Scopes defined in scope.
11381138 /// setDebugLoc - Replace current source information with new such.
11391139 /// Avoid using this, the constructor argument is preferable.
11401140 ///
1141 void setDebugLoc(const DebugLoc dl) { debugLoc = dl; }
1141 void setDebugLoc(const DebugLoc dl) {
1142 debugLoc = dl;
1143 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
1144 }
11421145
11431146 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
11441147 /// fewer operand than it started with.
164164 static char ID; // Pass identification, replacement for typeid
165165
166166 struct VariableDbgInfo {
167 TrackingVH Var;
168 TrackingVH Expr;
167 TrackingMDNodeRef Var;
168 TrackingMDNodeRef Expr;
169169 unsigned Slot;
170170 DebugLoc Loc;
171
172 VariableDbgInfo(MDNode *Var, MDNode *Expr, unsigned Slot, DebugLoc Loc)
173 : Var(Var), Expr(Expr), Slot(Slot), Loc(Loc) {}
171174 };
172175 typedef SmallVector VariableDbgInfoMapTy;
173176 VariableDbgInfoMapTy VariableDbgInfos;
392395 /// information of a variable.
393396 void setVariableDbgInfo(MDNode *Var, MDNode *Expr, unsigned Slot,
394397 DebugLoc Loc) {
395 VariableDbgInfo Info = {Var, Expr, Slot, Loc};
396 VariableDbgInfos.push_back(std::move(Info));
398 VariableDbgInfos.emplace_back(Var, Expr, Slot, Loc);
397399 }
398400
399401 VariableDbgInfoMapTy &getVariableDbgInfo() { return VariableDbgInfos; }
761761 ValueList(VTs.VTs), UseList(nullptr),
762762 NumOperands(Ops.size()), NumValues(VTs.NumVTs),
763763 debugLoc(dl), IROrder(Order) {
764 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
764765 assert(NumOperands == Ops.size() &&
765766 "NumOperands wasn't wide enough for its operands!");
766767 assert(NumValues == VTs.NumVTs &&
779780 SubclassData(0), NodeId(-1), OperandList(nullptr), ValueList(VTs.VTs),
780781 UseList(nullptr), NumOperands(0), NumValues(VTs.NumVTs), debugLoc(dl),
781782 IROrder(Order) {
783 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
782784 assert(NumValues == VTs.NumVTs &&
783785 "NumValues wasn't wide enough for its operands!");
784786 }
1717 #include "llvm/ADT/ArrayRef.h"
1818 #include "llvm/ADT/StringRef.h"
1919 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/TrackingMDRef.h"
2021 #include "llvm/IR/ValueHandle.h"
2122 #include "llvm/Support/DataTypes.h"
2223
6465 Function *DeclareFn; // llvm.dbg.declare
6566 Function *ValueFn; // llvm.dbg.value
6667
67 SmallVector AllEnumTypes;
68 /// Use TrackingVH to collect RetainTypes, since they can be updated
69 /// later on.
70 SmallVector, 4> AllRetainTypes;
71 SmallVector AllSubprograms;
72 SmallVector AllGVs;
73 SmallVector<TrackingVH, 4> AllImportedModules;
68 SmallVector<Metadata *, 4> AllEnumTypes;
69 /// Track the RetainTypes, since they can be updated later on.
70 SmallVector AllRetainTypes;
71 SmallVector AllSubprograms;
72 SmallVector AllGVs;
73 SmallVector AllImportedModules;
74
75 /// \brief Track nodes that may be unresolved.
76 SmallVector UnresolvedNodes;
77 bool AllowUnresolvedNodes;
7478
7579 /// Each subprogram's preserved local variables.
76 DenseMapVH>> PreservedVariables;
80 DenseMapMDNodeRef>> PreservedVariables;
7781
7882 DIBuilder(const DIBuilder &) LLVM_DELETED_FUNCTION;
7983 void operator=(const DIBuilder &) LLVM_DELETED_FUNCTION;
8084
85 /// \brief Create a temporary.
86 ///
87 /// Create an \a MDNodeFwdDecl and track it in \a UnresolvedNodes.
88 void trackIfUnresolved(MDNode *N);
89
8190 public:
82 explicit DIBuilder(Module &M);
91 /// \brief Construct a builder for a module.
92 ///
93 /// If \c AllowUnresolved, collect unresolved nodes attached to the module
94 /// in order to resolve cycles during \a finalize().
95 explicit DIBuilder(Module &M, bool AllowUnresolved = true);
8396 enum DebugEmissionKind { FullDebug=1, LineTablesOnly };
8497
8598 /// finalize - Construct any deferred debug info descriptors.
436449 DIBasicType createUnspecifiedParameter();
437450
438451 /// getOrCreateArray - Get a DIArray, create one if required.
439 DIArray getOrCreateArray(ArrayRef<Value *> Elements);
452 DIArray getOrCreateArray(ArrayRef<Metadata *> Elements);
440453
441454 /// getOrCreateTypeArray - Get a DITypeArray, create one if required.
442 DITypeArray getOrCreateTypeArray(ArrayRef<Value *> Elements);
455 DITypeArray getOrCreateTypeArray(ArrayRef<Metadata *> Elements);
443456
444457 /// getOrCreateSubrange - Create a descriptor for a value range. This
445458 /// implicitly uniques the values returned.
167167
168168 bool Verify() const;
169169
170 operator MDNode *() const { return const_cast(DbgNode); }
171 MDNode *operator->() const { return const_cast(DbgNode); }
170 MDNode *get() const { return const_cast(DbgNode); }
171 operator MDNode *() const { return get(); }
172 MDNode *operator->() const { return get(); }
172173
173174 // An explicit operator bool so that we can do testing of DI values
174175 // easily.
739740
740741 DIScopeRef getContext() const { return getFieldAs(1); }
741742 DITypeRef getType() const { return getFieldAs(2); }
742 Value *getValue() const;
743 Metadata *getValue() const;
743744 StringRef getFilename() const { return getFieldAs(4).getFilename(); }
744745 StringRef getDirectory() const {
745746 return getFieldAs(4).getDirectory();
1515 #define LLVM_IR_DEBUGLOC_H
1616
1717 #include "llvm/Support/DataTypes.h"
18 #include "llvm/IR/TrackingMDRef.h"
1819
1920 namespace llvm {
20 template struct DenseMapInfo;
21 class MDNode;
21
2222 class LLVMContext;
2323 class raw_ostream;
24 class MDNode;
2425
2526 /// DebugLoc - Debug location id. This is carried by Instruction, SDNode,
2627 /// and MachineInstr to compactly encode file/line/scope information for an
2728 /// operation.
2829 class DebugLoc {
29 friend struct DenseMapInfo;
30 TrackingMDNodeRef Loc;
3031
31 /// getEmptyKey() - A private constructor that returns an unknown that is
32 /// not equal to the tombstone key or DebugLoc().
33 static DebugLoc getEmptyKey() {
34 DebugLoc DL;
35 DL.LineCol = 1;
36 return DL;
32 public:
33 DebugLoc() {}
34 DebugLoc(DebugLoc &&X) : Loc(std::move(X.Loc)) {}
35 DebugLoc(const DebugLoc &X) : Loc(X.Loc) {}
36 DebugLoc &operator=(DebugLoc &&X) {
37 Loc = std::move(X.Loc);
38 return *this;
39 }
40 DebugLoc &operator=(const DebugLoc &X) {
41 Loc = X.Loc;
42 return *this;
3743 }
3844
39 /// getTombstoneKey() - A private constructor that returns an unknown that
40 /// is not equal to the empty key or DebugLoc().
41 static DebugLoc getTombstoneKey() {
42 DebugLoc DL;
43 DL.LineCol = 2;
44 return DL;
45 }
46
47 /// LineCol - This 32-bit value encodes the line and column number for the
48 /// location, encoded as 24-bits for line and 8 bits for col. A value of 0
49 /// for either means unknown.
50 uint32_t LineCol;
51
52 /// ScopeIdx - This is an opaque ID# for Scope/InlinedAt information,
53 /// decoded by LLVMContext. 0 is unknown.
54 int ScopeIdx;
55 public:
56 DebugLoc() : LineCol(0), ScopeIdx(0) {} // Defaults to unknown.
45 /// \brief Check whether this has a trivial destructor.
46 bool hasTrivialDestructor() const { return Loc.hasTrivialDestructor(); }
5747
5848 /// get - Get a new DebugLoc that corresponds to the specified line/col
5949 /// scope/inline location.
60 static DebugLoc get(unsigned Line, unsigned Col,
61 MDNode *Scope, MDNode *InlinedAt = nullptr);
50 static DebugLoc get(unsigned Line, unsigned Col, MDNode *Scope,
51 MDNode *InlinedAt = nullptr);
6252
6353 /// getFromDILocation - Translate the DILocation quad into a DebugLoc.
6454 static DebugLoc getFromDILocation(MDNode *N);
6757 static DebugLoc getFromDILexicalBlock(MDNode *N);
6858
6959 /// isUnknown - Return true if this is an unknown location.
70 bool isUnknown() const { return ScopeIdx == 0; }
60 bool isUnknown() const { return !Loc; }
7161
72 unsigned getLine() const {
73 return (LineCol << 8) >> 8; // Mask out column.
74 }
75
76 unsigned getCol() const {
77 return LineCol >> 24;
78 }
62 unsigned getLine() const;
63 unsigned getCol() const;
7964
8065 /// getScope - This returns the scope pointer for this DebugLoc, or null if
8166 /// invalid.
82 MDNode *getScope(const LLVMContext &Ctx) const;
67 MDNode *getScope() const;
68 MDNode *getScope(const LLVMContext &) const { return getScope(); }
8369
8470 /// getInlinedAt - This returns the InlinedAt pointer for this DebugLoc, or
8571 /// null if invalid or not present.
86 MDNode *getInlinedAt(const LLVMContext &Ctx) const;
72 MDNode *getInlinedAt() const;
73 MDNode *getInlinedAt(const LLVMContext &) const { return getInlinedAt(); }
8774
8875 /// getScopeAndInlinedAt - Return both the Scope and the InlinedAt values.
76 void getScopeAndInlinedAt(MDNode *&Scope, MDNode *&IA) const;
8977 void getScopeAndInlinedAt(MDNode *&Scope, MDNode *&IA,
90 const LLVMContext &Ctx) const;
78 const LLVMContext &) const {
79 return getScopeAndInlinedAt(Scope, IA);
80 }
9181
9282 /// getScopeNode - Get MDNode for DebugLoc's scope, or null if invalid.
93 MDNode *getScopeNode(const LLVMContext &Ctx) const;
83 MDNode *getScopeNode() const;
84 MDNode *getScopeNode(const LLVMContext &) const { return getScopeNode(); }
9485
9586 // getFnDebugLoc - Walk up the scope chain of given debug loc and find line
9687 // number info for the function.
97 DebugLoc getFnDebugLoc(const LLVMContext &Ctx) const;
88 DebugLoc getFnDebugLoc() const;
89 DebugLoc getFnDebugLoc(const LLVMContext &) const {
90 return getFnDebugLoc();
91 }
9892
9993 /// getAsMDNode - This method converts the compressed DebugLoc node into a
10094 /// DILocation compatible MDNode.
101 MDNode *getAsMDNode(const LLVMContext &Ctx) const;
95 MDNode *getAsMDNode() const;
96 MDNode *getAsMDNode(LLVMContext &) const { return getAsMDNode(); }
10297
103 bool operator==(const DebugLoc &DL) const {
104 return LineCol == DL.LineCol && ScopeIdx == DL.ScopeIdx;
105 }
98 bool operator==(const DebugLoc &DL) const { return Loc == DL.Loc; }
10699 bool operator!=(const DebugLoc &DL) const { return !(*this == DL); }
107100
108 void dump(const LLVMContext &Ctx) const;
101 void dump() const;
102 void dump(const LLVMContext &) const { dump(); }
109103 /// \brief prints source location /path/to/file.exe:line:col @[inlined at]
110 void print(const LLVMContext &Ctx, raw_ostream &OS) const;
104 void print(raw_ostream &OS) const;
105 void print(const LLVMContext &, raw_ostream &OS) const { print(OS); }
111106 };
112107
113 template <>
114 struct DenseMapInfo {
115 static DebugLoc getEmptyKey() { return DebugLoc::getEmptyKey(); }
116 static DebugLoc getTombstoneKey() { return DebugLoc::getTombstoneKey(); }
117 static unsigned getHashValue(const DebugLoc &Key);
118 static bool isEqual(DebugLoc LHS, DebugLoc RHS) { return LHS == RHS; }
119 };
120108 } // end namespace llvm
121109
122110 #endif /* LLVM_SUPPORT_DEBUGLOC_H */
2727 #include "llvm/IR/Function.h"
2828 #include "llvm/IR/Instructions.h"
2929 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Metadata.h"
3031
3132 namespace llvm {
3233 /// IntrinsicInst - A useful wrapper class for inspecting calls to intrinsic
8081 class DbgDeclareInst : public DbgInfoIntrinsic {
8182 public:
8283 Value *getAddress() const;
83 MDNode *getVariable() const { return cast(getArgOperand(1)); }
84 MDNode *getExpression() const { return cast(getArgOperand(2)); }
84 MDNode *getVariable() const {
85 return cast(
86 cast(getArgOperand(1))->getMetadata());
87 }
88 MDNode *getExpression() const {
89 return cast(
90 cast(getArgOperand(2))->getMetadata());
91 }
8592
8693 // Methods for support type inquiry through isa, cast, and dyn_cast:
8794 static inline bool classof(const IntrinsicInst *I) {
102109 return cast(
103110 const_cast(getArgOperand(1)))->getZExtValue();
104111 }
105 MDNode *getVariable() const { return cast(getArgOperand(2)); }
106 MDNode *getExpression() const { return cast(getArgOperand(3)); }
112 MDNode *getVariable() const {
113 return cast(
114 cast(getArgOperand(2))->getMetadata());
115 }
116 MDNode *getExpression() const {
117 return cast(
118 cast(getArgOperand(3))->getMetadata());
119 }
107120
108121 // Methods for support type inquiry through isa, cast, and dyn_cast:
109122 static inline bool classof(const IntrinsicInst *I) {
2323 class APInt;
2424 template class ArrayRef;
2525 class LLVMContext;
26 class Constant;
27 class ConstantAsMetadata;
2628 class MDNode;
2729 class MDString;
2830
3436
3537 /// \brief Return the given string as metadata.
3638 MDString *createString(StringRef Str);
39
40 /// \brief Return the given constant as metadata.
41 ConstantAsMetadata *createConstant(Constant *C);
3742
3843 //===------------------------------------------------------------------===//
3944 // FPMath metadata.
0 //===- llvm/Metadata.def - Metadata definitions -----------------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Macros for running through all types of metadata.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #if !(defined HANDLE_METADATA || defined HANDLE_METADATA_LEAF || \
14 defined HANDLE_METADATA_BRANCH)
15 #error "Missing macro definition of HANDLE_METADATA*"
16 #endif
17
18 // Handler for all types of metadata.
19 #ifndef HANDLE_METADATA
20 #define HANDLE_METADATA(CLASS)
21 #endif
22
23 // Handler for leaf nodes in the class hierarchy.
24 #ifndef HANDLE_METADATA_LEAF
25 #define HANDLE_METADATA_LEAF(CLASS) HANDLE_METADATA(CLASS)
26 #endif
27
28 // Handler for non-leaf nodes in the class hierarchy.
29 #ifndef HANDLE_METADATA_BRANCH
30 #define HANDLE_METADATA_BRANCH(CLASS) HANDLE_METADATA(CLASS)
31 #endif
32
33 HANDLE_METADATA_LEAF(MDString)
34 HANDLE_METADATA_BRANCH(ValueAsMetadata)
35 HANDLE_METADATA_LEAF(ConstantAsMetadata)
36 HANDLE_METADATA_LEAF(LocalAsMetadata)
37 HANDLE_METADATA_BRANCH(MDNode)
38 HANDLE_METADATA_LEAF(MDNodeFwdDecl)
39 HANDLE_METADATA_LEAF(GenericMDNode)
40
41 #undef HANDLE_METADATA
42 #undef HANDLE_METADATA_LEAF
43 #undef HANDLE_METADATA_BRANCH
1717
1818 #include "llvm/ADT/ArrayRef.h"
1919 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/FoldingSet.h"
2120 #include "llvm/ADT/ilist_node.h"
2221 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/IR/Constant.h"
23 #include "llvm/IR/MetadataTracking.h"
2324 #include "llvm/IR/Value.h"
2425 #include "llvm/Support/ErrorHandling.h"
26 #include
2527
2628 namespace llvm {
2729 class LLVMContext;
3739 /// \brief Root of the metadata hierarchy.
3840 ///
3941 /// This is a root class for typeless data in the IR.
40 ///
41 /// TODO: Detach from the Value hierarchy.
42 class Metadata : public Value {
42 class Metadata {
43 friend class ReplaceableMetadataImpl;
44
45 /// \brief RTTI.
46 const unsigned char SubclassID;
47
4348 protected:
44 Metadata(LLVMContext &Context, unsigned ID);
45
46 public:
49 /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
50 bool IsDistinctInContext : 1;
51 // TODO: expose remaining bits to subclasses.
52
53 unsigned short SubclassData16;
54 unsigned SubclassData32;
55
56 public:
57 enum MetadataKind {
58 GenericMDNodeKind,
59 MDNodeFwdDeclKind,
60 ConstantAsMetadataKind,
61 LocalAsMetadataKind,
62 MDStringKind
63 };
64
65 protected:
66 Metadata(unsigned ID)
67 : SubclassID(ID), IsDistinctInContext(false), SubclassData16(0),
68 SubclassData32(0) {}
69 ~Metadata() {}
70
71 /// \brief Store this in a big non-uniqued untyped bucket.
72 bool isStoredDistinctInContext() const { return IsDistinctInContext; }
73
74 /// \brief Default handling of a changed operand, which asserts.
75 ///
76 /// If subclasses pass themselves in as owners to a tracking node reference,
77 /// they must provide an implementation of this method.
78 void handleChangedOperand(void *, Metadata *) {
79 llvm_unreachable("Unimplemented in Metadata subclass");
80 }
81
82 public:
83 unsigned getMetadataID() const { return SubclassID; }
84
85 /// \brief User-friendly dump.
86 void dump() const;
87 void print(raw_ostream &OS) const;
88 void printAsOperand(raw_ostream &OS, bool PrintType = true,
89 const Module *M = nullptr) const;
90 };
91
92 #define HANDLE_METADATA(CLASS) class CLASS;
93 #include "llvm/IR/Metadata.def"
94
95 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
96 MD.print(OS);
97 return OS;
98 }
99
100 /// \brief Metadata wrapper in the Value hierarchy.
101 ///
102 /// A member of the \a Value hierarchy to represent a reference to metadata.
103 /// This allows, e.g., instrinsics to have metadata as operands.
104 ///
105 /// Notably, this is the only thing in either hierarchy that is allowed to
106 /// reference \a LocalAsMetadata.
107 class MetadataAsValue : public Value {
108 friend class ReplaceableMetadataImpl;
109 friend class LLVMContextImpl;
110
111 Metadata *MD;
112
113 MetadataAsValue(Type *Ty, Metadata *MD);
114 ~MetadataAsValue();
115
116 public:
117 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
118 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
119 Metadata *getMetadata() const { return MD; }
120
47121 static bool classof(const Value *V) {
48 return V->getValueID() == GenericMDNodeVal ||
49 V->getValueID() == MDNodeFwdDeclVal ||
50 V->getValueID() == MDStringVal;
51 }
52 };
122 return V->getValueID() == MetadataAsValueVal;
123 }
124
125 private:
126 void handleChangedMetadata(Metadata *MD);
127 void track();
128 void untrack();
129 };
130
131 /// \brief Shared implementation of use-lists for replaceable metadata.
132 ///
133 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
134 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
135 /// and \a TempMDNode).
136 class ReplaceableMetadataImpl {
137 friend class MetadataTracking;
138
139 public:
140 typedef MetadataTracking::OwnerTy OwnerTy;
141
142 private:
143 SmallDenseMap UseMap;
144
145 public:
146 ~ReplaceableMetadataImpl() {
147 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
148 }
149
150 /// \brief Replace all uses of this with MD.
151 ///
152 /// Replace all uses of this with \c MD, which is allowed to be null.
153 void replaceAllUsesWith(Metadata *MD);
154
155 /// \brief Resolve all uses of this.
156 ///
157 /// Resolve all uses of this, turning off RAUW permanently. If \c
158 /// ResolveUsers, call \a GenericMDNode::resolve() on any users whose last
159 /// operand is resolved.
160 void resolveAllUses(bool ResolveUsers = true);
161
162 private:
163 void addRef(void *Ref, OwnerTy Owner);
164 void dropRef(void *Ref);
165 void moveRef(void *Ref, void *New, const Metadata &MD);
166
167 static ReplaceableMetadataImpl *get(Metadata &MD);
168 };
169
170 /// \brief Value wrapper in the Metadata hierarchy.
171 ///
172 /// This is a custom value handle that allows other metadata to refer to
173 /// classes in the Value hierarchy.
174 ///
175 /// Because of full uniquing support, each value is only wrapped by a single \a
176 /// ValueAsMetadata object, so the lookup maps are far more efficient than
177 /// those using ValueHandleBase.
178 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
179 friend class ReplaceableMetadataImpl;
180 friend class LLVMContextImpl;
181
182 Value *V;
183
184 protected:
185 ValueAsMetadata(LLVMContext &Context, unsigned ID, Value *V)
186 : Metadata(ID), V(V) {
187 assert(V && "Expected valid value");
188 }
189 ~ValueAsMetadata() {}
190
191 public:
192 static ValueAsMetadata *get(Value *V);
193 static ConstantAsMetadata *getConstant(Value *C) {
194 return cast(get(C));
195 }
196 static LocalAsMetadata *getLocal(Value *Local) {
197 return cast(get(Local));
198 }
199
200 static ValueAsMetadata *getIfExists(Value *V);
201 static ConstantAsMetadata *getConstantIfExists(Value *C) {
202 return cast_or_null(getIfExists(C));
203 }
204 static LocalAsMetadata *getLocalIfExists(Value *Local) {
205 return cast_or_null(getIfExists(Local));
206 }
207
208 Value *getValue() const { return V; }
209 Type *getType() const { return V->getType(); }
210 LLVMContext &getContext() const { return V->getContext(); }
211
212 static void handleDeletion(Value *V);
213 static void handleRAUW(Value *From, Value *To);
214
215 protected:
216 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
217 ///
218 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
219 /// \a Value gets RAUW'ed and the target already exists, this is used to
220 /// merge the two metadata nodes.
221 void replaceAllUsesWith(Metadata *MD) {
222 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
223 }
224
225 public:
226 static bool classof(const Metadata *MD) {
227 return MD->getMetadataID() == LocalAsMetadataKind ||
228 MD->getMetadataID() == ConstantAsMetadataKind;
229 }
230 };
231
232 class ConstantAsMetadata : public ValueAsMetadata {
233 friend class ValueAsMetadata;
234
235 ConstantAsMetadata(LLVMContext &Context, Constant *C)
236 : ValueAsMetadata(Context, ConstantAsMetadataKind, C) {}
237
238 public:
239 static ConstantAsMetadata *get(Constant *C) {
240 return ValueAsMetadata::getConstant(C);
241 }
242 static ConstantAsMetadata *getIfExists(Constant *C) {
243 return ValueAsMetadata::getConstantIfExists(C);
244 }
245
246 Constant *getValue() const {
247 return cast(ValueAsMetadata::getValue());
248 }
249
250 static bool classof(const Metadata *MD) {
251 return MD->getMetadataID() == ConstantAsMetadataKind;
252 }
253 };
254
255 class LocalAsMetadata : public ValueAsMetadata {
256 friend class ValueAsMetadata;
257
258 LocalAsMetadata(LLVMContext &Context, Value *Local)
259 : ValueAsMetadata(Context, LocalAsMetadataKind, Local) {
260 assert(!isa(Local) && "Expected local value");
261 }
262
263 public:
264 static LocalAsMetadata *get(Value *Local) {
265 return ValueAsMetadata::getLocal(Local);
266 }
267 static LocalAsMetadata *getIfExists(Value *Local) {
268 return ValueAsMetadata::getLocalIfExists(Local);
269 }
270
271 static bool classof(const Metadata *MD) {
272 return MD->getMetadataID() == LocalAsMetadataKind;
273 }
274 };
275
276 /// \brief Transitional API for extracting constants from Metadata.
277 ///
278 /// This namespace contains transitional functions for metadata that points to
279 /// \a Constants.
280 ///
281 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
282 /// operands could refer to any \a Value. There's was a lot of code like this:
283 ///
284 /// \code
285 /// MDNode *N = ...;
286 /// auto *CI = dyn_cast(N->getOperand(2));
287 /// \endcode
288 ///
289 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
290 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
291 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
292 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
293 /// requires subtle control flow changes.
294 ///
295 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
296 /// so that metadata can refer to numbers without traversing a bridge to the \a
297 /// Value hierarchy. In this final state, the code above would look like this:
298 ///
299 /// \code
300 /// MDNode *N = ...;
301 /// auto *MI = dyn_cast(N->getOperand(2));
302 /// \endcode
303 ///
304 /// The API in this namespace supports the transition. \a MDInt doesn't exist
305 /// yet, and even once it does, changing each metadata schema to use it is its
306 /// own mini-project. In the meantime this API prevents us from introducing
307 /// complex and bug-prone control flow that will disappear in the end. In
308 /// particular, the above code looks like this:
309 ///
310 /// \code
311 /// MDNode *N = ...;
312 /// auto *CI = mdconst::dyn_extract(N->getOperand(2));
313 /// \endcode
314 ///
315 /// The full set of provided functions includes:
316 ///
317 /// mdconst::hasa <=> isa
318 /// mdconst::extract <=> cast
319 /// mdconst::extract_or_null <=> cast_or_null
320 /// mdconst::dyn_extract <=> dyn_cast
321 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
322 ///
323 /// The target of the cast must be a subclass of \a Constant.
324 namespace mdconst {
325
326 namespace detail {
327 template T &make();
328 template struct HasDereference {
329 typedef char Yes[1];
330 typedef char No[2];
331 template struct SFINAE {};
332
333 template
334 static Yes &hasDereference(SFINAE(*make()))> * = 0);
335 template static No &hasDereference(...);
336
337 static const bool value =
338 sizeof(hasDereference(nullptr)) == sizeof(Yes);
339 };
340 template struct IsValidPointer {
341 static const bool value = std::is_base_of::value &&
342 HasDereference::value;
343 };
344 template struct IsValidReference {
345 static const bool value = std::is_base_of::value &&
346 std::is_convertible::value;
347 };
348 } // end namespace detail
349
350 /// \brief Check whether Metadata has a Value.
351 ///
352 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
353 /// type \c X.
354 template
355 inline typename std::enable_if::value, bool>::type
356 hasa(Y &&MD) {
357 assert(MD && "Null pointer sent into hasa");
358 if (auto *V = dyn_cast(MD))
359 return isa(V->getValue());
360 return false;
361 }
362 template
363 inline
364 typename std::enable_if::value, bool>::type
365 hasa(Y &MD) {
366 return hasa(&MD);
367 }
368
369 /// \brief Extract a Value from Metadata.
370 ///
371 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
372 template
373 inline typename std::enable_if::value, X *>::type
374 extract(Y &&MD) {
375 return cast(cast(MD)->getValue());
376 }
377 template
378 inline
379 typename std::enable_if::value, X *>::type
380 extract(Y &MD) {
381 return extract(&MD);
382 }
383
384 /// \brief Extract a Value from Metadata, allowing null.
385 ///
386 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
387 /// from \c MD, allowing \c MD to be null.
388 template
389 inline typename std::enable_if::value, X *>::type
390 extract_or_null(Y &&MD) {
391 if (auto *V = cast_or_null(MD))
392 return cast(V->getValue());
393 return nullptr;
394 }
395
396 /// \brief Extract a Value from Metadata, if any.
397 ///
398 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
399 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
400 /// Value it does contain is of the wrong subclass.
401 template
402 inline typename std::enable_if::value, X *>::type
403 dyn_extract(Y &&MD) {
404 if (auto *V = dyn_cast(MD))
405 return dyn_cast(V->getValue());
406 return nullptr;
407 }
408
409 /// \brief Extract a Value from Metadata, if any, allowing null.
410 ///
411 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
412 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
413 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
414 template
415 inline typename std::enable_if::value, X *>::type
416 dyn_extract_or_null(Y &&MD) {
417 if (auto *V = dyn_cast_or_null(MD))
418 return dyn_cast(V->getValue());
419 return nullptr;
420 }
421
422 } // end namespace mdconst
53423
54424 //===----------------------------------------------------------------------===//
55425 /// \brief A single uniqued string.
59429 class MDString : public Metadata {
60430 friend class StringMapEntry;
61431
62 virtual void anchor();
63432 MDString(const MDString &) LLVM_DELETED_FUNCTION;
433 MDString &operator=(MDString &&) LLVM_DELETED_FUNCTION;
434 MDString &operator=(const MDString &) LLVM_DELETED_FUNCTION;
64435
65436 StringMapEntry *Entry;
66 explicit MDString(LLVMContext &Context)
67 : Metadata(Context, Value::MDStringVal), Entry(nullptr) {}
68
69 /// \brief Shadow Value::getName() to prevent its use.
70 StringRef getName() const LLVM_DELETED_FUNCTION;
437 MDString() : Metadata(MDStringKind), Entry(nullptr) {}
438 MDString(MDString &&) : Metadata(MDStringKind) {}
71439
72440 public:
73441 static MDString *get(LLVMContext &Context, StringRef Str);
88456 iterator end() const { return getString().end(); }
89457
90458 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
91 static bool classof(const Value *V) {
92 return V->getValueID() == MDStringVal;
459 static bool classof(const Metadata *MD) {
460 return MD->getMetadataID() == MDStringKind;
93461 }
94462 };
95463
137505 }
138506 };
139507
140 class MDNodeOperand;
508 /// \brief Tracking metadata reference owned by Metadata.
509 ///
510 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
511 /// of \a Metadata, which has the option of registering itself for callbacks to
512 /// re-unique itself.
513 ///
514 /// In particular, this is used by \a MDNode.
515 class MDOperand {
516 MDOperand(MDOperand &&) LLVM_DELETED_FUNCTION;
517 MDOperand(const MDOperand &) LLVM_DELETED_FUNCTION;
518 MDOperand &operator=(MDOperand &&) LLVM_DELETED_FUNCTION;
519 MDOperand &operator=(const MDOperand &) LLVM_DELETED_FUNCTION;
520
521 Metadata *MD;
522
523 public:
524 MDOperand() : MD(nullptr) {}
525 ~MDOperand() { untrack(); }
526
527 LLVM_EXPLICIT operator bool() const { return get(); }
528 Metadata *get() const { return MD; }
529 operator Metadata *() const { return get(); }
530 Metadata *operator->() const { return get(); }
531 Metadata &operator*() const { return *get(); }
532
533 void reset() {
534 untrack();
535 MD = nullptr;
536 }
537 void reset(Metadata *MD, Metadata *Owner) {
538 untrack();
539 this->MD = MD;
540 track(Owner);
541 }
542
543 private:
544 void track(Metadata *Owner) {
545 if (MD) {
546 if (Owner)
547 MetadataTracking::track(this, *MD, *Owner);
548 else
549 MetadataTracking::track(MD);
550 }
551 }
552 void untrack() {
553 assert(static_cast(this) == &MD && "Expected same address");
554 if (MD)
555 MetadataTracking::untrack(MD);
556 }
557 };
558
559 template <> struct simplify_type {
560 typedef Metadata *SimpleType;
561 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
562 };
563
564 template <> struct simplify_type {
565 typedef Metadata *SimpleType;
566 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
567 };
141568
142569 //===----------------------------------------------------------------------===//
143570 /// \brief Tuple of metadata.
144571 class MDNode : public Metadata {
145572 MDNode(const MDNode &) LLVM_DELETED_FUNCTION;
146573 void operator=(const MDNode &) LLVM_DELETED_FUNCTION;
147 friend class MDNodeOperand;
148 friend class LLVMContextImpl;
149574 void *operator new(size_t) LLVM_DELETED_FUNCTION;
150575
576 LLVMContext &Context;
577 unsigned NumOperands;
578
151579 protected:
580 unsigned MDNodeSubclassData;
581
152582 void *operator new(size_t Size, unsigned NumOps);
153583
154584 /// \brief Required by std, but never called.
164594 llvm_unreachable("Constructor throws?");
165595 }
166596
167 /// \brief Subclass data enums.
168 enum {
169 /// FunctionLocalBit - This bit is set if this MDNode is function local.
170 /// This is true when it (potentially transitively) contains a reference to
171 /// something in a function, like an argument, basicblock, or instruction.
172 FunctionLocalBit = 1 << 0,
173
174 /// NotUniquedBit - This is set on MDNodes that are not uniqued because they
175 /// have a null operand.
176 NotUniquedBit = 1 << 1
177 };
178
179 /// \brief FunctionLocal enums.
180 enum FunctionLocalness {
181 FL_Unknown = -1,
182 FL_No = 0,
183 FL_Yes = 1
184 };
185
186 /// \brief Replace each instance of the given operand with a new value.
187 void replaceOperand(MDNodeOperand *Op, Value *NewVal);
188
189 MDNode(LLVMContext &C, unsigned ID, ArrayRef Vals,
190 bool isFunctionLocal);
191 ~MDNode() {}
192
193 static MDNode *getMDNode(LLVMContext &C, ArrayRef Vals,
194 FunctionLocalness FL, bool Insert = true);
195 public:
196 static MDNode *get(LLVMContext &Context, ArrayRef Vals);
197 /// \brief Construct MDNode with an explicit function-localness.
198 ///
199 /// Don't analyze Vals; trust isFunctionLocal.
597 MDNode(LLVMContext &Context, unsigned ID, ArrayRef MDs);
598 ~MDNode() { dropAllReferences(); }
599
600 void dropAllReferences();
601 void storeDistinctInContext();
602
603 static MDNode *getMDNode(LLVMContext &C, ArrayRef MDs,
604 bool Insert = true);
605
606 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
607 MDOperand *mutable_end() { return reinterpret_cast(this); }
608
609 public:
610 static MDNode *get(LLVMContext &Context, ArrayRef MDs) {
611 return getMDNode(Context, MDs, true);
612 }
200613 static MDNode *getWhenValsUnresolved(LLVMContext &Context,
201 ArrayRef Vals,
202 bool isFunctionLocal);
203
204 static MDNode *getIfExists(LLVMContext &Context, ArrayRef Vals);
614 ArrayRef MDs) {
615 // TODO: Remove this.
616 return get(Context, MDs);
617 }
618
619 static MDNode *getIfExists(LLVMContext &Context, ArrayRef MDs) {
620 return getMDNode(Context, MDs, false);
621 }
205622
206623 /// \brief Return a temporary MDNode
207624 ///
208625 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
209626 /// not uniqued, may be RAUW'd, and must be manually deleted with
210627 /// deleteTemporary.
211 static MDNode *getTemporary(LLVMContext &Context, ArrayRef Vals);
628 static MDNodeFwdDecl *getTemporary(LLVMContext &Context,
629 ArrayRef MDs);
212630
213631 /// \brief Deallocate a node created by getTemporary.
214632 ///
215633 /// The node must not have any users.
216634 static void deleteTemporary(MDNode *N);
217635
636 LLVMContext &getContext() const { return Context; }
637
218638 /// \brief Replace a specific operand.
219 void replaceOperandWith(unsigned i, Value *NewVal);
220
221 /// \brief Return specified operand.
222 Value *getOperand(unsigned i) const LLVM_READONLY;
639 void replaceOperandWith(unsigned I, Metadata *New);
640
641 /// \brief Check if node is fully resolved.
642 bool isResolved() const;
643
644 protected:
645 /// \brief Set an operand.
646 ///
647 /// Sets the operand directly, without worrying about uniquing.
648 void setOperand(unsigned I, Metadata *New);
649
650 public:
651 typedef const MDOperand *op_iterator;
652 typedef iterator_range op_range;
653
654 op_iterator op_begin() const {
655 return const_cast(this)->mutable_begin();
656 }
657 op_iterator op_end() const {
658 return const_cast(this)->mutable_end();
659 }
660 op_range operands() const { return op_range(op_begin(), op_end()); }
661
662 const MDOperand &getOperand(unsigned I) const {
663 assert(I < NumOperands && "Out of range");
664 return op_begin()[I];
665 }
223666
224667 /// \brief Return number of MDNode operands.
225668 unsigned getNumOperands() const { return NumOperands; }
226669
227 /// \brief Return whether MDNode is local to a function.
228 bool isFunctionLocal() const {
229 return (getSubclassDataFromValue() & FunctionLocalBit) != 0;
230 }
231
232 /// \brief Return the first function-local operand's function.
233 ///
234 /// If this metadata is function-local and recursively has a function-local
235 /// operand, return the first such operand's parent function. Otherwise,
236 /// return null. getFunction() should not be used for performance- critical
237 /// code because it recursively visits all the MDNode's operands.
238 const Function *getFunction() const;
239
240670 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
241 static bool classof(const Value *V) {
242 return V->getValueID() == GenericMDNodeVal ||
243 V->getValueID() == MDNodeFwdDeclVal;
671 static bool classof(const Metadata *MD) {
672 return MD->getMetadataID() == GenericMDNodeKind ||
673 MD->getMetadataID() == MDNodeFwdDeclKind;
244674 }
245675
246676 /// \brief Check whether MDNode is a vtable access.
253683 static AAMDNodes getMostGenericAA(const AAMDNodes &A, const AAMDNodes &B);
254684 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
255685 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
256
257 protected:
258 bool isNotUniqued() const {
259 return (getSubclassDataFromValue() & NotUniquedBit) != 0;
260 }
261 void setIsNotUniqued();
262
263 // Shadow Value::setValueSubclassData with a private forwarding method so that
264 // any future subclasses cannot accidentally use it.
265 void setValueSubclassData(unsigned short D) {
266 Value::setValueSubclassData(D);
267 }
268686 };
269687
270688 /// \brief Generic metadata node.
278696 /// TODO: Make uniquing opt-out (status: mandatory, sometimes dropped).
279697 /// TODO: Drop support for RAUW.
280698 class GenericMDNode : public MDNode {
699 friend class Metadata;
281700 friend class MDNode;
282701 friend class LLVMContextImpl;
283
284 unsigned Hash;
285
286 GenericMDNode(LLVMContext &C, ArrayRef Vals, bool isFunctionLocal)
287 : MDNode(C, GenericMDNodeVal, Vals, isFunctionLocal), Hash(0) {}
702 friend class ReplaceableMetadataImpl;
703
704 /// \brief Support RAUW as long as one of its arguments is replaceable.
705 ///
706 /// If an operand is an \a MDNodeFwdDecl (or a replaceable \a GenericMDNode),
707 /// support RAUW to support uniquing as forward declarations are resolved.
708 /// As soon as operands have been resolved, drop support.
709 ///
710 /// FIXME: Save memory by storing this in a pointer union with the
711 /// LLVMContext, and adding an LLVMContext reference to RMI.
712 std::unique_ptr ReplaceableUses;
713
714 GenericMDNode(LLVMContext &C, ArrayRef Vals);
288715 ~GenericMDNode();
289716
290 void dropAllReferences();
717 void setHash(unsigned Hash) { MDNodeSubclassData = Hash; }
291718
292719 public:
293720 /// \brief Get the hash, if any.
294 unsigned getHash() const { return Hash; }
295
296 static bool classof(const Value *V) {
297 return V->getValueID() == GenericMDNodeVal;
298 }
721 unsigned getHash() const { return MDNodeSubclassData; }
722
723 static bool classof(const Metadata *MD) {
724 return MD->getMetadataID() == GenericMDNodeKind;
725 }
726
727 /// \brief Check whether any operands are forward declarations.
728 ///
729 /// Returns \c true as long as any operands (or their operands, etc.) are \a
730 /// MDNodeFwdDecl.
731 ///
732 /// As forward declarations are resolved, their containers should get
733 /// resolved automatically. However, if this (or one of its operands) is
734 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
735 bool isResolved() const { return !ReplaceableUses; }
736
737 /// \brief Resolve cycles.
738 ///
739 /// Once all forward declarations have been resolved, force cycles to be
740 /// resolved.
741 ///
742 /// \pre No operands (or operands' operands, etc.) are \a MDNodeFwdDecl.
743 void resolveCycles();
744
745 private:
746 void handleChangedOperand(void *Ref, Metadata *New);
747
748 bool hasUnresolvedOperands() const { return SubclassData32; }
749 void incrementUnresolvedOperands() { ++SubclassData32; }
750 void decrementUnresolvedOperands() { --SubclassData32; }
751 void resolve();
299752 };
300753
301754 /// \brief Forward declaration of metadata.
303756 /// Forward declaration of metadata, in the form of a metadata node. Unlike \a
304757 /// GenericMDNode, this class has support for RAUW and is suitable for forward
305758 /// references.
306 class MDNodeFwdDecl : public MDNode {
759 class MDNodeFwdDecl : public MDNode, ReplaceableMetadataImpl {
760 friend class Metadata;
307761 friend class MDNode;
308
309 MDNodeFwdDecl(LLVMContext &C, ArrayRef Vals, bool isFunctionLocal)
310 : MDNode(C, MDNodeFwdDeclVal, Vals, isFunctionLocal) {}
762 friend class ReplaceableMetadataImpl;
763
764 MDNodeFwdDecl(LLVMContext &C, ArrayRef Vals)
765 : MDNode(C, MDNodeFwdDeclKind, Vals) {}
311766 ~MDNodeFwdDecl() {}
312767
313768 public:
314 static bool classof(const Value *V) {
315 return V->getValueID() == MDNodeFwdDeclVal;
316 }
769 static bool classof(const Metadata *MD) {
770 return MD->getMetadataID() == MDNodeFwdDeclKind;
771 }
772
773 using ReplaceableMetadataImpl::replaceAllUsesWith;
317774 };
318775
319776 //===----------------------------------------------------------------------===//
332789
333790 std::string Name;
334791 Module *Parent;
335 void *Operands; // SmallVectorVH, 4>
792 void *Operands; // SmallVectorMDRef, 4>
336793
337794 void setParent(Module *M) { Parent = M; }
338795
0 //===- llvm/IR/MetadataTracking.h - Metadata tracking ---------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Low-level functions to enable tracking of metadata that could RAUW.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_IR_METADATATRACKING_H
14 #define LLVM_IR_METADATATRACKING_H
15
16 #include "llvm/ADT/PointerUnion.h"
17 #include "llvm/Support/Casting.h"
18 #include
19
20 namespace llvm {
21
22 class Metadata;
23 class MetadataAsValue;
24
25 /// \brief API for tracking metadata references through RAUW and deletion.
26 ///
27 /// Shared API for updating \a Metadata pointers in subclasses that support
28 /// RAUW.
29 ///
30 /// This API is not meant to be used directly. See \a TrackingMDRef for a
31 /// user-friendly tracking reference.
32 class MetadataTracking {
33 public:
34 /// \brief Track the reference to metadata.
35 ///
36 /// Register \c MD with \c *MD, if the subclass supports tracking. If \c *MD
37 /// gets RAUW'ed, \c MD will be updated to the new address. If \c *MD gets
38 /// deleted, \c MD will be set to \c nullptr.
39 ///
40 /// If tracking isn't supported, \c *MD will not change.
41 ///
42 /// \return true iff tracking is supported by \c MD.
43 static bool track(Metadata *&MD) {
44 return track(&MD, *MD, static_cast(nullptr));
45 }
46
47 /// \brief Track the reference to metadata for \a Metadata.
48 ///
49 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
50 /// tell it that its operand changed. This could trigger \c Owner being
51 /// re-uniqued.
52 static bool track(void *Ref, Metadata &MD, Metadata &Owner) {
53 return track(Ref, MD, &Owner);
54 }
55
56 /// \brief Track the reference to metadata for \a MetadataAsValue.
57 ///
58 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
59 /// tell it that its operand changed. This could trigger \c Owner being
60 /// re-uniqued.
61 static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner) {
62 return track(Ref, MD, &Owner);
63 }
64
65 /// \brief Stop tracking a reference to metadata.
66 ///
67 /// Stops \c *MD from tracking \c MD.
68 static void untrack(Metadata *&MD) { untrack(&MD, *MD); }
69 static void untrack(void *Ref, Metadata &MD);
70
71 /// \brief Move tracking from one reference to another.
72 ///
73 /// Semantically equivalent to \c untrack(MD) followed by \c track(New),
74 /// except that ownership callbacks are maintained.
75 ///
76 /// Note: it is an error if \c *MD does not equal \c New.
77 ///
78 /// \return true iff tracking is supported by \c MD.
79 static bool retrack(Metadata *&MD, Metadata *&New) {
80 return retrack(&MD, *MD, &New);
81 }
82 static bool retrack(void *Ref, Metadata &MD, void *New);
83
84 /// \brief Check whether metadata is replaceable.
85 static bool isReplaceable(const Metadata &MD);
86
87 typedef PointerUnion OwnerTy;
88
89 private:
90 /// \brief Track a reference to metadata for an owner.
91 ///
92 /// Generalized version of tracking.
93 static bool track(void *Ref, Metadata &MD, OwnerTy Owner);
94 };
95
96 } // end namespace llvm
97
98 #endif
187187 ModFlagBehaviorLastVal = AppendUnique
188188 };
189189
190 /// Checks if Value represents a valid ModFlagBehavior, and stores the
190 /// Checks if Metadata represents a valid ModFlagBehavior, and stores the
191191 /// converted result in MFB.
192 static bool isValidModFlagBehavior(Value *V, ModFlagBehavior &MFB);
192 static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB);
193193
194194 struct ModuleFlagEntry {
195195 ModFlagBehavior Behavior;
196196 MDString *Key;
197 Value *Val;
198 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Value *V)
199 : Behavior(B), Key(K), Val(V) {}
197 Metadata *Val;
198 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Metadata *V)
199 : Behavior(B), Key(K), Val(V) {}
200200 };
201201
202202 /// @}
441441
442442 /// Return the corresponding value if Key appears in module flags, otherwise
443443 /// return null.
444 Value *getModuleFlag(StringRef Key) const;
444 Metadata *getModuleFlag(StringRef Key) const;
445445
446446 /// Returns the NamedMDNode in the module that represents module-level flags.
447447 /// This method returns null if there are no module-level flags.
454454
455455 /// Add a module-level flag to the module-level flags metadata. It will create
456456 /// the module-level flags named metadata if it doesn't already exist.
457 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val);
457 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
458 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Constant *Val);
458459 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
459460 void addModuleFlag(MDNode *Node);
460461
0 //===- llvm/IR/TrackingMDRef.h - Tracking Metadata references -------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // References to metadata that track RAUW.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_IR_TRACKINGMDREF_H
14 #define LLVM_IR_TRACKINGMDREF_H
15
16 #include "llvm/IR/MetadataTracking.h"
17 #include "llvm/Support/Casting.h"
18
19 namespace llvm {
20
21 class Metadata;
22 class MDNode;
23 class ValueAsMetadata;
24
25 /// \brief Tracking metadata reference.
26 ///
27 /// This class behaves like \a TrackingVH, but for metadata.
28 class TrackingMDRef {
29 Metadata *MD;
30
31 public:
32 TrackingMDRef() : MD(nullptr) {}
33 explicit TrackingMDRef(Metadata *MD) : MD(MD) { track(); }
34
35 TrackingMDRef(TrackingMDRef &&X) : MD(X.MD) { retrack(X); }
36 TrackingMDRef(const TrackingMDRef &X) : MD(X.MD) { track(); }
37 TrackingMDRef &operator=(TrackingMDRef &&X) {
38 if (&X == this)
39 return *this;
40
41 untrack();
42 MD = X.MD;
43 retrack(X);
44 return *this;
45 }
46 TrackingMDRef &operator=(const TrackingMDRef &X) {
47 if (&X == this)
48 return *this;
49
50 untrack();
51 MD = X.MD;
52 track();
53 return *this;
54 }
55 ~TrackingMDRef() { untrack(); }
56
57 LLVM_EXPLICIT operator bool() const { return get(); }
58 Metadata *get() const { return MD; }
59 operator Metadata *() const { return get(); }
60 Metadata *operator->() const { return get(); }
61 Metadata &operator*() const { return *get(); }
62
63 void reset() {
64 untrack();
65 MD = nullptr;
66 }
67 void reset(Metadata *MD) {
68 untrack();
69 this->MD = MD;
70 track();
71 }
72
73 /// \brief Check whether this has a trivial destructor.
74 ///
75 /// If \c MD isn't replaceable, the destructor will be a no-op.
76 bool hasTrivialDestructor() const {
77 return !MD || !MetadataTracking::isReplaceable(*MD);
78 }
79
80 private:
81 void track() {
82 if (MD)
83 MetadataTracking::track(MD);
84 }
85 void untrack() {
86 if (MD)
87 MetadataTracking::untrack(MD);
88 }
89 void retrack(TrackingMDRef &X) {
90 assert(MD == X.MD && "Expected values to match");
91 if (X.MD) {
92 MetadataTracking::retrack(X.MD, MD);
93 X.MD = nullptr;
94 }
95 }
96 };
97
98 /// \brief Typed tracking ref.
99 ///
100 /// Track refererences of a particular type. It's useful to use this for \a
101 /// MDNode and \a ValueAsMetadata.
102 template class TypedTrackingMDRef {
103 TrackingMDRef Ref;
104
105 public:
106 TypedTrackingMDRef() {}
107 explicit TypedTrackingMDRef(T *MD) : Ref(static_cast(MD)) {}
108
109 TypedTrackingMDRef(TypedTrackingMDRef &&X) : Ref(std::move(X.Ref)) {}
110 TypedTrackingMDRef(const TypedTrackingMDRef &X) : Ref(X.Ref) {}
111 TypedTrackingMDRef &operator=(TypedTrackingMDRef &&X) {
112 Ref = std::move(X.Ref);
113 return *this;
114 }
115 TypedTrackingMDRef &operator=(const TypedTrackingMDRef &X) {
116 Ref = X.Ref;
117 return *this;
118 }
119
120 LLVM_EXPLICIT operator bool() const { return get(); }
121 T *get() const { return (T *)Ref.get(); }
122 operator T *() const { return get(); }
123 T *operator->() const { return get(); }
124 T &operator*() const { return *get(); }
125
126 void reset() { Ref.reset(); }
127 void reset(T *MD) { Ref.reset(static_cast(MD)); }
128
129 /// \brief Check whether this has a trivial destructor.
130 bool hasTrivialDestructor() const { return Ref.hasTrivialDestructor(); }
131 };
132
133 typedef TypedTrackingMDRef TrackingMDNodeRef;
134 typedef TypedTrackingMDRef TrackingValueAsMetadataRef;
135
136 // Expose the underlying metadata to casting.
137 template <> struct simplify_type {
138 typedef Metadata *SimpleType;
139 static SimpleType getSimplifiedValue(TrackingMDRef &MD) { return MD.get(); }
140 };
141
142 template <> struct simplify_type {
143 typedef Metadata *SimpleType;
144 static SimpleType getSimplifiedValue(const TrackingMDRef &MD) {
145 return MD.get();
146 }
147 };
148
149 template struct simplify_type> {
150 typedef T *SimpleType;
151 static SimpleType getSimplifiedValue(TypedTrackingMDRef &MD) {
152 return MD.get();
153 }
154 };
155
156 template struct simplify_type> {
157 typedef T *SimpleType;
158 static SimpleType getSimplifiedValue(const TypedTrackingMDRef &MD) {
159 return MD.get();
160 }
161 };
162
163 } // end namespace llvm
164
165 #endif
3030 // To avoid walking constant expressions multiple times and other IR
3131 // objects, we keep several helper maps.
3232 DenseSet VisitedConstants;
33 DenseSet VisitedMetadata;
3334 DenseSet VisitedTypes;
3435
3536 std::vector StructTypes;
3636 class InlineAsm;
3737 class Instruction;
3838 class LLVMContext;
39 class MDNode;
4039 class Module;
4140 class StringRef;
4241 class Twine;
6968 Type *VTy;
7069 Use *UseList;
7170
72 friend class ValueSymbolTable; // Allow ValueSymbolTable to directly mod Name.
71 friend class ValueAsMetadata; // Allow access to NameAndIsUsedByMD.
7372 friend class ValueHandleBase;
74 ValueName *Name;
73 PointerIntPair NameAndIsUsedByMD;
7574
7675 const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
7776 unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
225224 LLVMContext &getContext() const;
226225
227226 // \brief All values can potentially be named.
228 bool hasName() const { return Name != nullptr; }
229 ValueName *getValueName() const { return Name; }
230 void setValueName(ValueName *VN) { Name = VN; }
231
227 bool hasName() const { return getValueName() != nullptr; }
228 ValueName *getValueName() const { return NameAndIsUsedByMD.getPointer(); }
229 void setValueName(ValueName *VN) { NameAndIsUsedByMD.setPointer(VN); }
230
231 private:
232 void destroyValueName();
233
234 public:
232235 /// \brief Return a constant reference to the value's name.
233236 ///
234237 /// This is cheap and guaranteed to return the same reference as long as the
351354 ConstantStructVal, // This is an instance of ConstantStruct
352355 ConstantVectorVal, // This is an instance of ConstantVector
353356 ConstantPointerNullVal, // This is an instance of ConstantPointerNull
354 GenericMDNodeVal, // This is an instance of GenericMDNode
355 MDNodeFwdDeclVal, // This is an instance of MDNodeFwdDecl
356 MDStringVal, // This is an instance of MDString
357 MetadataAsValueVal, // This is an instance of MetadataAsValue
357358 InlineAsmVal, // This is an instance of InlineAsm
358359 InstructionVal, // This is an instance of Instruction
359360 // Enum values starting at InstructionVal are used for Instructions;
403404 /// \brief Return true if there is a value handle associated with this value.
404405 bool hasValueHandle() const { return HasValueHandle; }
405406
407 /// \brief Return true if there is metadata referencing this value.
408 bool isUsedByMetadata() const { return NameAndIsUsedByMD.getInt(); }
409
406410 /// \brief Strip off pointer casts, all-zero GEPs, and aliases.
407411 ///
408412 /// Returns the original uncasted value. If this is called on a non-pointer
686690 }
687691 };
688692
689 template <> struct isa_impl {
690 static inline bool doit(const Value &Val) {
691 return Val.getValueID() == Value::GenericMDNodeVal ||
692 Val.getValueID() == Value::MDNodeFwdDeclVal;
693 }
694 };
695
696693 // Value* is only 4-byte aligned.
697694 template<>
698695 class PointerLikeTypeTraits {
2626 #define LLVM_IR_VALUEMAP_H
2727
2828 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/IR/TrackingMDRef.h"
2930 #include "llvm/IR/ValueHandle.h"
3031 #include "llvm/Support/Mutex.h"
3132 #include "llvm/Support/UniqueLock.h"
7879 friend class ValueMapCallbackVH;
7980 typedef ValueMapCallbackVH ValueMapCVH;
8081 typedef DenseMap > MapT;
82 typedef DenseMap MDMapT;
8183 typedef typename Config::ExtraData ExtraData;
8284 MapT Map;
85 std::unique_ptr MDMap;
8386 ExtraData Data;
8487 ValueMap(const ValueMap&) LLVM_DELETED_FUNCTION;
8588 ValueMap& operator=(const ValueMap&) LLVM_DELETED_FUNCTION;
9093 typedef unsigned size_type;
9194
9295 explicit ValueMap(unsigned NumInitBuckets = 64)
93 : Map(NumInitBuckets), Data() {}
96 : Map(NumInitBuckets), Data() {}
9497 explicit ValueMap(const ExtraData &Data, unsigned NumInitBuckets = 64)
95 : Map(NumInitBuckets), Data(Data) {}
98 : Map(NumInitBuckets), Data(Data) {}
9699
97100 ~ValueMap() {}
101
102 bool hasMD() const { return MDMap; }
103 MDMapT &MD() {
104 if (!MDMap)
105 MDMap.reset(new MDMapT);
106 return *MDMap;
107 }
98108
99109 typedef ValueMapIterator iterator;
100110 typedef ValueMapConstIterator const_iterator;
109119 /// Grow the map so that it has at least Size buckets. Does not shrink
110120 void resize(size_t Size) { Map.resize(Size); }
111121
112 void clear() { Map.clear(); }
122 void clear() {
123 Map.clear();
124 MDMap.reset();
125 }
113126
114127 /// Return 1 if the specified key is in the map, 0 otherwise.
115128 size_type count(const KeyT &Val) const {
7070 ValueMapTypeRemapper *TypeMapper = nullptr,
7171 ValueMaterializer *Materializer = nullptr);
7272
73 Metadata *MapValue(const Metadata *MD, ValueToValueMapTy &VM,
74 RemapFlags Flags = RF_None,
75 ValueMapTypeRemapper *TypeMapper = nullptr,
76 ValueMaterializer *Materializer = nullptr);
77
78 /// MapValue - provide versions that preserve type safety for MDNodes.
79 MDNode *MapValue(const MDNode *MD, ValueToValueMapTy &VM,
80 RemapFlags Flags = RF_None,
81 ValueMapTypeRemapper *TypeMapper = nullptr,
82 ValueMaterializer *Materializer = nullptr);
83
7384 void RemapInstruction(Instruction *I, ValueToValueMapTy &VM,
7485 RemapFlags Flags = RF_None,
7586 ValueMapTypeRemapper *TypeMapper = nullptr,
7687 ValueMaterializer *Materializer = nullptr);
7788
78 /// MapValue - provide versions that preserve type safety for MDNode and
79 /// Constants.
80 inline MDNode *MapValue(const MDNode *V, ValueToValueMapTy &VM,
81 RemapFlags Flags = RF_None,
82 ValueMapTypeRemapper *TypeMapper = nullptr,
83 ValueMaterializer *Materializer = nullptr) {
84 return cast(MapValue((const Value*)V, VM, Flags, TypeMapper,
85 Materializer));
86 }
89 /// MapValue - provide versions that preserve type safety for Constants.
8790 inline Constant *MapValue(const Constant *V, ValueToValueMapTy &VM,
8891 RemapFlags Flags = RF_None,
8992 ValueMapTypeRemapper *TypeMapper = nullptr,
11561156 macro(Argument) \
11571157 macro(BasicBlock) \
11581158 macro(InlineAsm) \
1159 macro(MDNode) \
1160 macro(MDString) \
11611159 macro(User) \
11621160 macro(Constant) \
11631161 macro(BlockAddress) \
13051303 #define LLVM_DECLARE_VALUE_CAST(name) \
13061304 LLVMValueRef LLVMIsA##name(LLVMValueRef Val);
13071305 LLVM_FOR_EACH_VALUE_SUBCLASS(LLVM_DECLARE_VALUE_CAST)
1306
1307 LLVMValueRef LLVMIsAMDNode(LLVMValueRef Val);
1308 LLVMValueRef LLVMIsAMDString(LLVMValueRef Val);
13081309
13091310 /**
13101311 * @}
195195 SmallVector Weights;
196196 Weights.reserve(TI->getNumSuccessors());
197197 for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
198 ConstantInt *Weight = dyn_cast(WeightsNode->getOperand(i));
198 ConstantInt *Weight =
199 mdconst::dyn_extract(WeightsNode->getOperand(i));
199200 if (!Weight)
200201 return false;
201202 Weights.push_back(
37493749 assert(NumRanges >= 1);
37503750
37513751 for (unsigned i = 0; i < NumRanges; ++i) {
3752 ConstantInt *Lower = cast(MD->getOperand(2*i + 0));
3753 ConstantInt *Upper = cast(MD->getOperand(2*i + 1));
3752 ConstantInt *Lower =
3753 mdconst::extract(MD->getOperand(2 * i + 0));
3754 ConstantInt *Upper =
3755 mdconst::extract(MD->getOperand(2 * i + 1));
37543756 ConstantRange Range(Lower->getValue(), Upper->getValue());
37553757 TotalRange = TotalRange.unionWith(Range);
37563758 }
166166 bool TypeIsImmutable() const {
167167 if (Node->getNumOperands() < 3)
168168 return false;
169 ConstantInt *CI = dyn_cast(Node->getOperand(2));
169 ConstantInt *CI = mdconst::dyn_extract(Node->getOperand(2));
170170 if (!CI)
171171 return false;
172172 return CI->getValue()[0];
193193 return dyn_cast_or_null(Node->getOperand(1));
194194 }
195195 uint64_t getOffset() const {
196 return cast(Node->getOperand(2))->getZExtValue();
196 return mdconst::extract(Node->getOperand(2))->getZExtValue();
197197 }
198198 /// TypeIsImmutable - Test if this TBAAStructTagNode represents a type for
199199 /// objects which are not modified (by any means) in the context where this
201201 bool TypeIsImmutable() const {
202202 if (Node->getNumOperands() < 4)
203203 return false;
204 ConstantInt *CI = dyn_cast(Node->getOperand(3));
204 ConstantInt *CI = mdconst::dyn_extract(Node->getOperand(3));
205205 if (!CI)
206206 return false;
207207 return CI->getValue()[0];
232232 // Fast path for a scalar type node and a struct type node with a single
233233 // field.
234234 if (Node->getNumOperands() <= 3) {
235 uint64_t Cur = Node->getNumOperands() == 2 ? 0 :
236 cast(Node->getOperand(2))->getZExtValue();
235 uint64_t Cur = Node->getNumOperands() == 2
236 ? 0
237 : mdconst::extract(Node->getOperand(2))
238 ->getZExtValue();
237239 Offset -= Cur;
238240 MDNode *P = dyn_cast_or_null(Node->getOperand(1));
239241 if (!P)
245247 // the current offset is bigger than the given offset.
246248 unsigned TheIdx = 0;
247249 for (unsigned Idx = 1; Idx < Node->getNumOperands(); Idx += 2) {
248 uint64_t Cur = cast(Node->getOperand(Idx + 1))->
249 getZExtValue();
250 uint64_t Cur = mdconst::extract(Node->getOperand(Idx + 1))
251 ->getZExtValue();
250252 if (Cur > Offset) {
251253 assert(Idx >= 3 &&
252254 "TBAAStructTypeNode::getParent should have an offset match!");
257259 // Move along the last field.
258260 if (TheIdx == 0)
259261 TheIdx = Node->getNumOperands() - 2;
260 uint64_t Cur = cast(Node->getOperand(TheIdx + 1))->
261 getZExtValue();
262 uint64_t Cur = mdconst::extract(Node->getOperand(TheIdx + 1))
263 ->getZExtValue();
262264 Offset -= Cur;
263265 MDNode *P = dyn_cast_or_null(Node->getOperand(TheIdx));
264266 if (!P)
607609 return nullptr;
608610 // We need to convert from a type node to a tag node.
609611 Type *Int64 = IntegerType::get(A->getContext(), 64);
610 Value *Ops[3] = { Ret, Ret, ConstantInt::get(Int64, 0) };
612 Metadata *Ops[3] = {Ret, Ret,
613 ConstantAsMetadata::get(ConstantInt::get(Int64, 0))};
611614 return MDNode::get(A->getContext(), Ops);
612615 }
613616
311311 // Use the high end of the ranges to find leading zeros.
312312 unsigned MinLeadingZeros = BitWidth;
313313 for (unsigned i = 0; i < NumRanges; ++i) {
314 ConstantInt *Lower = cast(Ranges.getOperand(2*i + 0));
315 ConstantInt *Upper = cast(Ranges.getOperand(2*i + 1));
314 ConstantInt *Lower =
315 mdconst::extract(Ranges.getOperand(2 * i + 0));
316 ConstantInt *Upper =
317 mdconst::extract(Ranges.getOperand(2 * i + 1));
316318 ConstantRange Range(Lower->getValue(), Upper->getValue());
317319 if (Range.isWrappedSet())
318320 MinLeadingZeros = 0; // -1 has no zeros
15031505 const unsigned NumRanges = Ranges->getNumOperands() / 2;
15041506 assert(NumRanges >= 1);
15051507 for (unsigned i = 0; i < NumRanges; ++i) {
1506 ConstantInt *Lower = cast(Ranges->getOperand(2*i + 0));
1507 ConstantInt *Upper = cast(Ranges->getOperand(2*i + 1));
1508 ConstantInt *Lower =
1509 mdconst::extract(Ranges->getOperand(2 * i + 0));
1510 ConstantInt *Upper =
1511 mdconst::extract(Ranges->getOperand(2 * i + 1));
15081512 ConstantRange Range(Lower->getValue(), Upper->getValue());
15091513 if (Range.contains(Value))
15101514 return false;
6161 NumberedMetadata[SlotNo] == nullptr)
6262 return Error(MDList[i].Loc, "use of undefined metadata '!" +
6363 Twine(SlotNo) + "'");
64 assert(!NumberedMetadata[SlotNo]->isFunctionLocal() &&
65 "Unexpected function-local metadata");
6664 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
6765 }
6866 }
168166 "use of undefined metadata '!" +
169167 Twine(ForwardRefMDNodes.begin()->first) + "'");
170168
169 // Resolve metadata cycles.
170 for (auto &N : NumberedMetadata)
171 if (auto *G = cast_or_null(N))
172 G->resolveCycles();
171173
172174 // Look for intrinsic functions and CallInst that need to be upgraded
173175 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
560562 if (Result) return false;
561563
562564 // Otherwise, create MDNode forward reference.
563 MDNode *FwdNode = MDNode::getTemporary(Context, None);
565 MDNodeFwdDecl *FwdNode = MDNode::getTemporary(Context, None);
564566 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
565567
566568 if (NumberedMetadata.size() <= MID)
567569 NumberedMetadata.resize(MID+1);
568 NumberedMetadata[MID] = FwdNode;
570 NumberedMetadata[MID].reset(FwdNode);
569571 Result = FwdNode;
570572 return false;
571573 }
608610
609611 LocTy TyLoc;
610612 Type *Ty = nullptr;
611 SmallVector Elts;
613 MDNode *Init;
612614 if (ParseUInt32(MetadataID) ||
613615 ParseToken(lltok::equal, "expected '=' here") ||
614616 ParseType(Ty, TyLoc) ||
615617 ParseToken(lltok::exclaim, "Expected '!' here") ||
616 ParseToken(lltok::lbrace, "Expected '{' here") ||
617 ParseMDNodeVector(Elts, nullptr) ||
618 ParseToken(lltok::rbrace, "expected end of metadata node"))
619 return true;
620
621 MDNode *Init = MDNode::get(Context, Elts);
618 ParseMDNode(Init))
619 return true;
622620
623621 // See if this was forward referenced, if so, handle it.
624 std::map, LocTy> >::iterator
625 FI = ForwardRefMDNodes.find(MetadataID);
622 auto FI = ForwardRefMDNodes.find(MetadataID);
626623 if (FI != ForwardRefMDNodes.end()) {
627 MDNode *Temp = FI->second.first;
624 auto *Temp = FI->second.first;
628625 Temp->replaceAllUsesWith(Init);
629626 MDNode::deleteTemporary(Temp);
630627 ForwardRefMDNodes.erase(FI);
636633
637634 if (NumberedMetadata[MetadataID] != nullptr)
638635 return TokError("Metadata id is already used");
639 NumberedMetadata[MetadataID] = Init;
636 NumberedMetadata[MetadataID].reset(Init);
640637 }
641638
642639 return false;
15261523 if (ParseToken(lltok::exclaim, "expected '!' here"))
15271524 return true;
15281525
1529 // This code is similar to that of ParseMetadataValue, however it needs to
1526 // This code is similar to that of ParseMetadata, however it needs to
15301527 // have special-case code for a forward reference; see the comments on
15311528 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
15321529 // at the top level here.
15331530 if (Lex.getKind() == lltok::lbrace) {
1534 ValID ID;
1535 if (ParseMetadataListValue(ID, PFS))
1531 MDNode *N;
1532 if (ParseMDNode(N))
15361533 return true;
1537 assert(ID.Kind == ValID::t_MDNode);
1538 if (ID.MDNodeVal->isFunctionLocal())
1539 return Error(Loc, "unexpected function-local metadata");
1540 Inst->setMetadata(MDK, ID.MDNodeVal);
1534 Inst->setMetadata(MDK, N);
15411535 } else {
15421536 unsigned NodeID = 0;
15431537 if (ParseMDNodeID(Node, NodeID))
23942388 ID.Kind = ValID::t_LocalName;
23952389 break;
23962390 case lltok::exclaim: // !42, !{...}, or !"foo"
2397 return ParseMetadataValue(ID, PFS);
2391 return ParseMetadataAsValue(ID, PFS);
23982392 case lltok::APSInt:
23992393 ID.APSIntVal = Lex.getAPSIntVal();
24002394 ID.Kind = ValID::t_APSInt;
29342928 return false;
29352929 }
29362930
2937 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2938 assert(Lex.getKind() == lltok::lbrace);
2939 Lex.Lex();
2940
2941 SmallVector Elts;
2942 if (ParseMDNodeVector(Elts, PFS) ||
2943 ParseToken(lltok::rbrace, "expected end of metadata node"))
2944 return true;
2945
2946 ID.MDNodeVal = MDNode::get(Context, Elts);
2947 ID.Kind = ValID::t_MDNode;
2948 return false;
2949 }
2950
2951 /// ParseMetadataValue
2931 bool LLParser::ParseMDNode(MDNode *&MD) {
2932 SmallVector Elts;
2933 if (ParseMDNodeVector(Elts, nullptr))
2934 return true;
2935
2936 MD = MDNode::get(Context, Elts);
2937 return false;
2938 }
2939
2940 bool LLParser::ParseMDNodeOrLocal(Metadata *&MD, PerFunctionState *PFS) {
2941 SmallVector Elts;
2942 if (ParseMDNodeVector(Elts, PFS))
2943 return true;
2944
2945 // Check for function-local metadata masquerading as an MDNode.
2946 if (PFS && Elts.size() == 1 && Elts[0] && isa(Elts[0])) {
2947 MD = Elts[0];
2948 return false;
2949 }
2950
2951 MD = MDNode::get(Context, Elts);
2952 return false;
2953 }
2954
2955 bool LLParser::ParseMetadataAsValue(ValID &ID, PerFunctionState *PFS) {
2956 Metadata *MD;
2957 if (ParseMetadata(MD, PFS))
2958 return true;
2959
2960 ID.Kind = ValID::t_Metadata;
2961 ID.MetadataVal = MetadataAsValue::get(Context, MD);
2962 return false;
2963 }
2964
2965 /// ParseMetadata
29522966 /// ::= !42
29532967 /// ::= !{...}
29542968 /// ::= !"string"
2955 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2969 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
29562970 assert(Lex.getKind() == lltok::exclaim);
29572971 Lex.Lex();
29582972
29592973 // MDNode:
29602974 // !{ ... }
29612975 if (Lex.getKind() == lltok::lbrace)
2962 return ParseMetadataListValue(ID, PFS);
2976 return ParseMDNodeOrLocal(MD, PFS);
29632977
29642978 // Standalone metadata reference
29652979 // !42
29662980 if (Lex.getKind() == lltok::APSInt) {
2967 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2968 ID.Kind = ValID::t_MDNode;
2981 MDNode *N;
2982 if (ParseMDNodeID(N))
2983 return true;
2984 MD = N;
29692985 return false;
29702986 }
29712987
29722988 // MDString:
29732989 // ::= '!' STRINGCONSTANT
2974 if (ParseMDString(ID.MDStringVal)) return true;
2975 ID.Kind = ValID::t_MDString;
2990 MDString *S;
2991 if (ParseMDString(S))
2992 return true;
2993 MD = S;
29762994 return false;
29772995 }
29782996
30053023 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
30063024 return false;
30073025 }
3008 case ValID::t_MDNode:
3026 case ValID::t_Metadata:
30093027 if (!Ty->isMetadataTy())
30103028 return Error(ID.Loc, "metadata value must have metadata type");
3011 V = ID.MDNodeVal;
3012 return false;
3013 case ValID::t_MDString:
3014 if (!Ty->isMetadataTy())
3015 return Error(ID.Loc, "metadata value must have metadata type");
3016 V = ID.MDStringVal;
3029 V = ID.MetadataVal;
30173030 return false;
30183031 case ValID::t_GlobalName:
30193032 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
46674680 //===----------------------------------------------------------------------===//
46684681
46694682 /// ParseMDNodeVector
4670 /// ::= Element (',' Element)*
4683 /// ::= { Element (',' Element)* }
46714684 /// Element
46724685 /// ::= 'null' | TypeAndValue
4673 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4686 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts,
46744687 PerFunctionState *PFS) {
4688 assert(Lex.getKind() == lltok::lbrace);
4689 Lex.Lex();
4690
46754691 // Check for an empty list.
4676 if (Lex.getKind() == lltok::rbrace)
4692 if (EatIfPresent(lltok::rbrace))
46774693 return false;
46784694
46794695 bool IsLocal = false;
46874703 continue;
46884704 }
46894705
4706 Type *Ty = nullptr;
4707 if (ParseType(Ty))
4708 return true;
4709
4710 if (Ty->isMetadataTy()) {
4711 // No function-local metadata here.
4712 Metadata *MD = nullptr;
4713 if (ParseMetadata(MD, nullptr))
4714 return true;
4715 Elts.push_back(MD);
4716 continue;
4717 }
4718
46904719 Value *V = nullptr;
4691 if (ParseTypeAndValue(V, PFS)) return true;
4692 Elts.push_back(V);
4693
4694 if (isa(V) && cast(V)->isFunctionLocal())
4695 return TokError("unexpected nested function-local metadata");
4696 if (!V->getType()->isMetadataTy() && !isa(V)) {
4720 if (ParseValue(Ty, V, PFS))
4721 return true;
4722 assert(V && "Expected valid value");
4723 Elts.push_back(ValueAsMetadata::get(V));
4724
4725 if (isa(Elts.back())) {
46974726 assert(PFS && "Unexpected function-local metadata without PFS");
46984727 if (Elts.size() > 1)
46994728 return TokError("unexpected function-local metadata");
47014730 }
47024731 } while (EatIfPresent(lltok::comma));
47034732
4704 return false;
4733 return ParseToken(lltok::rbrace, "expected end of metadata node");
47054734 }
47064735
47074736 //===----------------------------------------------------------------------===//
5151 t_EmptyArray, // No value: []
5252 t_Constant, // Value in ConstantVal.
5353 t_InlineAsm, // Value in StrVal/StrVal2/UIntVal.
54 t_MDNode, // Value in MDNodeVal.
55 t_MDString, // Value in MDStringVal.
54 t_Metadata, // Value in MetadataVal.
5655 t_ConstantStruct, // Value in ConstantStructElts.
5756 t_PackedConstantStruct // Value in ConstantStructElts.
5857 } Kind;
6362 APSInt APSIntVal;
6463 APFloat APFloatVal;
6564 Constant *ConstantVal;
66 MDNode *MDNodeVal;
67 MDString *MDStringVal;
65 MetadataAsValue *MetadataVal;
6866 Constant **ConstantStructElts;
6967
7068 ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
114112 StringMap > NamedTypes;
115113 std::vector > NumberedTypes;
116114
117 std::vector > NumberedMetadata;
118 std::map, LocTy> > ForwardRefMDNodes;
115 std::vector NumberedMetadata;
116 std::map> ForwardRefMDNodes;
119117
120118 // Global Value reference information.
121119 std::map > ForwardRefVals;
381379 bool ParseGlobalTypeAndValue(Constant *&V);
382380 bool ParseGlobalValueVector(SmallVectorImpl &Elts);
383381 bool parseOptionalComdat(Comdat *&C);
384 bool ParseMetadataListValue(ValID &ID, PerFunctionState *PFS);
385 bool ParseMetadataValue(ValID &ID, PerFunctionState *PFS);
386 bool ParseMDNodeVector(SmallVectorImpl &, PerFunctionState *PFS);
382 bool ParseMetadataAsValue(ValID &ID, PerFunctionState *PFS);
383 bool ParseMetadata(Metadata *&MD, PerFunctionState *PFS);
384 bool ParseMDNode(MDNode *&MD);
385 bool ParseMDNodeOrLocal(Metadata *&MD, PerFunctionState *PFS);
386 bool ParseMDNodeVector(SmallVectorImpl &,
387 PerFunctionState *PFS);
387388 bool ParseInstructionMetadata(Instruction *Inst, PerFunctionState *PFS);
388389
389390 // Function Parsing.
437437 }
438438 }
439439
440 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
440 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
441441 if (Idx == size()) {
442 push_back(V);
442 push_back(MD);
443443 return;
444444 }
445445
446446 if (Idx >= size())
447447 resize(Idx+1);
448448
449 WeakVH &OldV = MDValuePtrs[Idx];
450 if (!OldV) {
451 OldV = V;
449 TrackingMDRef &OldMD = MDValuePtrs[Idx];
450 if (!OldMD) {
451 OldMD.reset(MD);
452452 return;
453453 }
454454
455455 // If there was a forward reference to this value, replace it.
456 MDNode *PrevVal = cast(OldV);
457 OldV->replaceAllUsesWith(V);
458 MDNode::deleteTemporary(PrevVal);
459 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
460 // value for Idx.
461 MDValuePtrs[Idx] = V;
462 }
463
464 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
456 MDNodeFwdDecl *PrevMD = cast(OldMD.get());
457 PrevMD->replaceAllUsesWith(MD);
458 MDNode::deleteTemporary(PrevMD);
459 --NumFwdRefs;
460 }
461
462 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
465463 if (Idx >= size())
466464 resize(Idx + 1);
467465
468 if (Value *V = MDValuePtrs[Idx]) {
469 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
470 return V;
471 }
466 if (Metadata *MD = MDValuePtrs[Idx])
467 return MD;
472468
473469 // Create and return a placeholder, which will later be RAUW'd.
474 Value *V = MDNode::getTemporary(Context, None);
475 MDValuePtrs[Idx] = V;
476 return V;
470 AnyFwdRefs = true;
471 ++NumFwdRefs;
472 Metadata *MD = MDNode::getTemporary(Context, None);
473 MDValuePtrs[Idx].reset(MD);
474 return MD;
475 }
476
477 void BitcodeReaderMDValueList::tryToResolveCycles() {
478 if (!AnyFwdRefs)
479 // Nothing to do.
480 return;
481
482 if (NumFwdRefs)
483 // Still forward references... can't resolve cycles.
484 return;
485
486 // Resolve any cycles.
487 for (auto &MD : MDValuePtrs) {
488 assert(!(MD && isa(MD)) && "Unexpected forward reference");
489 if (auto *G = dyn_cast_or_null(MD))
490 G->resolveCycles();
491 }
477492 }
478493
479494 Type *BitcodeReader::getTypeByID(unsigned ID) {
10651080 case BitstreamEntry::Error:
10661081 return Error(BitcodeError::MalformedBlock);
10671082 case BitstreamEntry::EndBlock:
1083 MDValueList.tryToResolveCycles();
10681084 return std::error_code();
10691085 case BitstreamEntry::Record:
10701086 // The interesting case.
10991115 break;
11001116 }
11011117 case bitc::METADATA_FN_NODE: {
1102 // This is a function-local node.
1118 // This is a LocalAsMetadata record, the only type of function-local
1119 // metadata.
11031120 if (Record.size() % 2 == 1)
11041121 return Error(BitcodeError::InvalidRecord);
11051122
1106 // If this isn't a single-operand node that directly references
1107 // non-metadata, we're dropping it. This used to be legal, but there's
1108 // no upgrade path.
1123 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1124 // to be legal, but there's no upgrade path.
11091125 auto dropRecord = [&] {
11101126 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
11111127 };
11201136 break;
11211137 }
11221138
1123 Value *Elts[] = {ValueList.getValueFwdRef(Record[1], Ty)};
1124 Value *V = MDNode::getWhenValsUnresolved(Context, Elts,
1125 /*IsFunctionLocal*/ true);
1126 MDValueList.AssignValue(V, NextMDValueNo++);
1139 MDValueList.AssignValue(
1140 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1141 NextMDValueNo++);
11271142 break;
11281143 }
11291144 case bitc::METADATA_NODE: {
11311146 return Error(BitcodeError::InvalidRecord);
11321147
11331148 unsigned Size = Record.size();
1134 SmallVector<Value*, 8> Elts;
1149 SmallVector<Metadata *, 8> Elts;
11351150 for (unsigned i = 0; i != Size; i += 2) {
11361151 Type *Ty = getTypeByID(Record[i]);
11371152 if (!Ty)
11381153 return Error(BitcodeError::InvalidRecord);
11391154 if (Ty->isMetadataTy())
11401155 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1141 else if (!Ty->isVoidTy())
1142 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1143 else
1156 else if (!Ty->isVoidTy()) {
1157 auto *MD =
1158 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1159 assert(isa(MD) &&
1160 "Expected non-function-local metadata");
1161 Elts.push_back(MD);
1162 } else
11441163 Elts.push_back(nullptr);
11451164 }
1146 Value *V = MDNode::getWhenValsUnresolved(Context, Elts,
1147 /*IsFunctionLocal*/ false);
1148 MDValueList.AssignValue(V, NextMDValueNo++);
1165 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
11491166 break;
11501167 }
11511168 case bitc::METADATA_STRING: {
11521169 std::string String(Record.begin(), Record.end());
11531170 llvm::UpgradeMDStringConstant(String);
1154 Value *V = MDString::get(Context, String);
1155 MDValueList.AssignValue(V, NextMDValueNo++);
1171 Metadata *MD = MDString::get(Context, String);
1172 MDValueList.AssignValue(MD, NextMDValueNo++);
11561173 break;
11571174 }
11581175 case bitc::METADATA_KIND: {
23582375 MDKindMap.find(Kind);
23592376 if (I == MDKindMap.end())
23602377 return Error(BitcodeError::InvalidID);
2361 MDNode *Node = cast(MDValueList.getValueFwdRef(Record[i+1]));
2362 if (Node->isFunctionLocal())
2378 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2379 if (isa(Node))
23632380 // Drop the attachment. This used to be legal, but there's no
23642381 // upgrade path.
23652382 break;
2366 Inst->setMetadata(I->second, Node);
2383 Inst->setMetadata(I->second, cast(Node));
23672384 if (I->second == LLVMContext::MD_tbaa)
23682385 InstsWithTBAATag.push_back(Inst);
23692386 }
1818 #include "llvm/Bitcode/LLVMBitCodes.h"
1919 #include "llvm/IR/Attributes.h"
2020 #include "llvm/IR/GVMaterializer.h"
21 #include "llvm/IR/Metadata.h"
2122 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/TrackingMDRef.h"
2224 #include "llvm/IR/Type.h"
2325 #include "llvm/IR/ValueHandle.h"
2426 #include
9496 //===----------------------------------------------------------------------===//
9597
9698 class BitcodeReaderMDValueList {
97 std::vector MDValuePtrs;
99 unsigned NumFwdRefs;
100 bool AnyFwdRefs;
101 std::vector MDValuePtrs;
98102
99103 LLVMContext &Context;
100104 public:
101 BitcodeReaderMDValueList(LLVMContext& C) : Context(C) {}
105 BitcodeReaderMDValueList(LLVMContext &C)
106 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
102107
103108 // vector compatibility methods
104109 unsigned size() const { return MDValuePtrs.size(); }
105110 void resize(unsigned N) { MDValuePtrs.resize(N); }
106 void push_back(Value *V) { MDValuePtrs.push_back(V); }
111 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
107112 void clear() { MDValuePtrs.clear(); }
108 Value *back() const { return MDValuePtrs.back(); }
113 Metadata *back() const { return MDValuePtrs.back(); }
109114 void pop_back() { MDValuePtrs.pop_back(); }
110115 bool empty() const { return MDValuePtrs.empty(); }
111116
112 Value *operator[](unsigned i) const {
117 Metadata *operator[](unsigned i) const {
113118 assert(i < MDValuePtrs.size());
114119 return MDValuePtrs[i];
115120 }
119124 MDValuePtrs.resize(N);
120125 }
121126
122 Value *getValueFwdRef(unsigned Idx);
123 void AssignValue(Value *V, unsigned Idx);
127 Metadata *getValueFwdRef(unsigned Idx);
128 void AssignValue(Metadata *MD, unsigned Idx);
129 void tryToResolveCycles();
124130 };
125131
126132 class BitcodeReader : public GVMaterializer {
247253 Type *getTypeByID(unsigned ID);
248254 Value *getFnValueByID(unsigned ID, Type *Ty) {
249255 if (Ty && Ty->isMetadataTy())
250 return MDValueList.getValueFwdRef(ID);
256 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
251257 return ValueList.getValueFwdRef(ID, Ty);
258 }
259 Metadata *getFnMetadataByID(unsigned ID) {
260 return MDValueList.getValueFwdRef(ID);
252261 }
253262 BasicBlock *getBasicBlock(unsigned ID) const {
254263 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
736736 return Flags;
737737 }
738738
739 static void WriteValueAsMetadataImpl(const ValueAsMetadata *MD,
740 const ValueEnumerator &VE,
741 BitstreamWriter &Stream,
742 SmallVectorImpl &Record,
743 unsigned Code) {
744 // Mimic an MDNode with a value as one operand.
745 Value *V = MD->getValue();
746 Record.push_back(VE.getTypeID(V->getType()));
747 Record.push_back(VE.getValueID(V));
748 Stream.EmitRecord(Code, Record, 0);
749 Record.clear();
750 }
751
752 static void WriteLocalAsMetadata(const LocalAsMetadata *MD,
753 const ValueEnumerator &VE,
754 BitstreamWriter &Stream,
755 SmallVectorImpl &Record) {
756 WriteValueAsMetadataImpl(MD, VE, Stream, Record, bitc::METADATA_FN_NODE);
757 }
758
759 static void WriteConstantAsMetadata(const ConstantAsMetadata *MD,
760 const ValueEnumerator &VE,
761 BitstreamWriter &Stream,
762 SmallVectorImpl &Record) {
763 WriteValueAsMetadataImpl(MD, VE, Stream, Record, bitc::METADATA_NODE);
764 }
765
739766 static void WriteMDNode(const MDNode *N,
740767 const ValueEnumerator &VE,
741768 BitstreamWriter &Stream,
742769 SmallVectorImpl &Record) {
743770 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
744 if (N->getOperand(i)) {
745 Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
746 Record.push_back(VE.getValueID(N->getOperand(i)));
747 } else {
771 Metadata *MD = N->getOperand(i);
772 if (!MD) {
748773 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
749774 Record.push_back(0);
750 }
751 }
752 unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
753 bitc::METADATA_NODE;
754 Stream.EmitRecord(MDCode, Record, 0);
775 continue;
776 }
777 if (auto *V = dyn_cast(MD)) {
778 Record.push_back(VE.getTypeID(V->getValue()->getType()));
779 Record.push_back(VE.getValueID(V->getValue()));
780 continue;
781 }
782 assert(!isa(MD) && "Unexpected function-local metadata");
783 Record.push_back(VE.getTypeID(Type::getMetadataTy(N->getContext())));
784 Record.push_back(VE.getMetadataID(MD));
785 }
786 Stream.EmitRecord(bitc::METADATA_NODE, Record, 0);
755787 Record.clear();
756788 }
757789
758790 static void WriteModuleMetadata(const Module *M,
759791 const ValueEnumerator &VE,
760792 BitstreamWriter &Stream) {
761 const auto &Vals = VE.getMDValues();
793 const auto &MDs = VE.getMDs();
762794 bool StartedMetadataBlock = false;
763795 unsigned MDSAbbrev = 0;
764796 SmallVector Record;
765 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
766
767 if (const MDNode *N = dyn_cast(Vals[i])) {
768 if (!N->isFunctionLocal() || !N->getFunction()) {
769 if (!StartedMetadataBlock) {
770 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
771 StartedMetadataBlock = true;
772 }
773 WriteMDNode(N, VE, Stream, Record);
797 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
798 if (const MDNode *N = dyn_cast(MDs[i])) {
799 if (!StartedMetadataBlock) {
800 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
801 StartedMetadataBlock = true;
774802 }
775 } else if (const MDString *MDS = dyn_cast(Vals[i])) {
776 if (!StartedMetadataBlock) {
803 WriteMDNode(N, VE, Stream, Record);
804 } else if (const auto *MDC = dyn_cast(MDs[i])) {
805 if (!StartedMetadataBlock) {
806 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
807 StartedMetadataBlock = true;
808 }
809 WriteConstantAsMetadata(MDC, VE, Stream, Record);
810 } else if (const MDString *MDS = dyn_cast(MDs[i])) {
811 if (!StartedMetadataBlock) {
777812 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
778813
779814 // Abbrev for METADATA_STRING.
812847
813848 // Write named metadata operands.
814849 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
815 Record.push_back(VE.getValueID(NMD->getOperand(i)));
850 Record.push_back(VE.getMetadataID(NMD->getOperand(i)));
816851 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
817852 Record.clear();
818853 }
826861 BitstreamWriter &Stream) {
827862 bool StartedMetadataBlock = false;
828863 SmallVector Record;
829 const SmallVectorImpl &Vals = VE.getFunctionLocalMDValues();
830 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
831 if (const MDNode *N = Vals[i])
832 if (N->isFunctionLocal() && N->getFunction() == &F) {
833 if (!StartedMetadataBlock) {
834 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
835 StartedMetadataBlock = true;
836 }
837 WriteMDNode(N, VE, Stream, Record);
838 }
864 const SmallVectorImpl &MDs =
865 VE.getFunctionLocalMDs();
866 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
867 assert(MDs[i] && "Expected valid function-local metadata");
868 if (!StartedMetadataBlock) {
869 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
870 StartedMetadataBlock = true;
871 }
872 WriteLocalAsMetadata(MDs[i], VE, Stream, Record);
873 }
839874
840875 if (StartedMetadataBlock)
841876 Stream.ExitBlock();
865900
866901 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
867902 Record.push_back(MDs[i].first);
868 Record.push_back(VE.getValueID(MDs[i].second));
903 Record.push_back(VE.getMetadataID(MDs[i].second));
869904 }
870905 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
871906 Record.clear();
16851720 } else {
16861721 MDNode *Scope, *IA;
16871722 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1723 assert(Scope && "Expected valid scope");
16881724
16891725 Vals.push_back(DL.getLine());
16901726 Vals.push_back(DL.getCol());
1691 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1692 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1727 Vals.push_back(Scope ? VE.getMetadataID(Scope) + 1 : 0);
1728 Vals.push_back(IA ? VE.getMetadataID(IA) + 1 : 0);
16931729 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
16941730 Vals.clear();
16951731
325325 if (I->hasPrologueData())
326326 EnumerateValue(I->getPrologueData());
327327
328 // Enumerate the metadata type.
329 //
330 // TODO: Move this to ValueEnumerator::EnumerateOperandType() once bitcode
331 // only encodes the metadata type when it's used as a value.
332 EnumerateType(Type::getMetadataTy(M.getContext()));
333
328334 // Insert constants and metadata that are named at module level into the slot
329335 // pool so that the module symbol table can refer to them...
330336 EnumerateValueSymbolTable(M.getValueSymbolTable());
340346 for (const BasicBlock &BB : F)
341347 for (const Instruction &I : BB) {
342348 for (const Use &Op : I.operands()) {
343 if (MDNode *MD = dyn_cast(&Op))
344 if (MD->isFunctionLocal() && MD->getFunction())
345 // These will get enumerated during function-incorporation.
346 continue;
347 EnumerateOperandType(Op);
349 auto *MD = dyn_cast(&Op);
350 if (!MD) {
351 EnumerateOperandType(Op);
352 continue;
353 }
354
355 // Local metadata is enumerated during function-incorporation.
356 if (isa(MD->getMetadata()))
357 continue;
358
359 EnumerateMetadata(MD->getMetadata());
348360 }
349361 EnumerateType(I.getType());
350362 if (const CallInst *CI = dyn_cast(&I))
388400 }
389401
390402 unsigned ValueEnumerator::getValueID(const Value *V) const {
391 if (isa(V) || isa(V)) {
392 ValueMapType::const_iterator I = MDValueMap.find(V);
393 assert(I != MDValueMap.end() && "Value not in slotcalculator!");
394 return I->second-1;
395 }
403 if (auto *MD = dyn_cast(V))
404 return getMetadataID(MD->getMetadata());
396405
397406 ValueMapType::const_iterator I = ValueMap.find(V);
398407 assert(I != ValueMap.end() && "Value not in slotcalculator!");
399408 return I->second-1;
409 }
410
411 unsigned ValueEnumerator::getMetadataID(const Metadata *MD) const {
412 auto I = MDValueMap.find(MD);
413 assert(I != MDValueMap.end() && "Metadata not in slotcalculator!");
414 return I->second - 1;
400415 }
401416
402417 void ValueEnumerator::dump() const {
432447
433448 }
434449 OS << "\n\n";
450 }
451 }
452
453 void ValueEnumerator::print(raw_ostream &OS, const MetadataMapType &Map,
454 const char *Name) const {
455
456 OS << "Map Name: " << Name << "\n";
457 OS << "Size: " << Map.size() << "\n";
458 for (auto I = Map.begin(), E = Map.end(); I != E; ++I) {
459 const Metadata *MD = I->first;
460 OS << "Metadata: slot = " << I->second << "\n";
461 MD->dump();
435462 }
436463 }
437464
492519 /// and types referenced by the given MDNode.
493520 void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
494521 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
495 if (Value *V = N->getOperand(i)) {
496 if (isa(V) || isa(V))
497 EnumerateMetadata(V);
498 else if (!isa(V) && !isa(V))
499 EnumerateValue(V);
500 } else
522 Metadata *MD = N->getOperand(i);
523 if (!MD) {
501524 EnumerateType(Type::getVoidTy(N->getContext()));
502 }
503 }
504
505 void ValueEnumerator::EnumerateMetadata(const Value *MD) {
506 assert((isa(MD) || isa(MD)) && "Invalid metadata kind");
507
508 // Skip function-local nodes themselves, but walk their operands.
509 const MDNode *N = dyn_cast(MD);
510 if (N && N->isFunctionLocal() && N->getFunction()) {
511 EnumerateMDNodeOperands(N);
512 return;
513 }
525 continue;
526 }
527 assert(!isa(MD) && "MDNodes cannot be function-local");
528 if (auto *C = dyn_cast(MD)) {
529 EnumerateValue(C->getValue());
530 continue;
531 }
532 EnumerateMetadata(MD);
533 }
534 }
535
536 void ValueEnumerator::EnumerateMetadata(const Metadata *MD) {
537 assert(
538 (isa(MD) || isa(MD) || isa(MD)) &&
539 "Invalid metadata kind");
514540
515541 // Insert a dummy ID to block the co-recursive call to
516542 // EnumerateMDNodeOperands() from re-visiting MD in a cyclic graph.
519545 if (!MDValueMap.insert(std::make_pair(MD, 0)).second)
520546 return;
521547
522 // Enumerate the type of this value.
523 EnumerateType(MD->getType());
524
525548 // Visit operands first to minimize RAUW.
526 if (N)
549 if (auto *N = dyn_cast(MD))
527550 EnumerateMDNodeOperands(N);
551 else if (auto *C = dyn_cast(MD))
552 EnumerateValue(C->getValue());
528553
529554 // Replace the dummy ID inserted above with the correct one. MDValueMap may
530555 // have changed by inserting operands, so we need a fresh lookup here.
531 MDValues.push_back(MD);
532 MDValueMap[MD] = MDValues.size();
556 MDs.push_back(MD);
557 MDValueMap[MD] = MDs.size();
533558 }
534559
535560 /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
536 /// information reachable from the given MDNode.
537 void ValueEnumerator::EnumerateFunctionLocalMetadata(const MDNode *N) {
538 assert(N->isFunctionLocal() && N->getFunction() &&
539 "EnumerateFunctionLocalMetadata called on non-function-local mdnode!");
540
541 // Enumerate the type of this value.
542 EnumerateType(N->getType());
543
561 /// information reachable from the metadata.
562 void ValueEnumerator::EnumerateFunctionLocalMetadata(
563 const LocalAsMetadata *Local) {
544564 // Check to see if it's already in!
545 unsigned &MDValueID = MDValueMap[N];
565 unsigned &MDValueID = MDValueMap[Local];
546566 if (MDValueID)
547567 return;
548568
549 MDValues.push_back(N);
550 MDValueID = MDValues.size();
551
552 // To incoroporate function-local information visit all function-local
553 // MDNodes and all function-local values they reference.
554 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
555 if (Value *V = N->getOperand(i)) {
556 if (MDNode *O = dyn_cast(V)) {
557 if (O->isFunctionLocal() && O->getFunction())
558 EnumerateFunctionLocalMetadata(O);
559 } else if (isa(V) || isa(V))
560 EnumerateValue(V);
561 }
562
563 // Also, collect all function-local MDNodes for easy access.
564 FunctionLocalMDs.push_back(N);
569 MDs.push_back(Local);
570 MDValueID = MDs.size();
571
572 EnumerateValue(Local->getValue());
573
574 // Also, collect all function-local metadata for easy access.
575 FunctionLocalMDs.push_back(Local);
565576 }
566577
567578 void ValueEnumerator::EnumerateValue(const Value *V) {
568579 assert(!V->getType()->isVoidTy() && "Can't insert void values!");
569 assert(!isa(V) && !isa(V) &&
570 "EnumerateValue doesn't handle Metadata!");
580 assert(!isa(V) && "EnumerateValue doesn't handle Metadata!");
571581
572582 // Check to see if it's already in!
573583 unsigned &ValueID = ValueMap[V];
656666 void ValueEnumerator::EnumerateOperandType(const Value *V) {
657667 EnumerateType(V->getType());
658668
659 if (const Constant *C = dyn_cast(V)) {
660 // If this constant is already enumerated, ignore it, we know its type must
661 // be enumerated.
662 if (ValueMap.count(V)) return;
663
664 // This constant may have operands, make sure to enumerate the types in
665 // them.
666 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
667 const Value *Op = C->getOperand(i);
668
669 // Don't enumerate basic blocks here, this happens as operands to
670 // blockaddress.
671 if (isa(Op)) continue;
672
673 EnumerateOperandType(Op);
674 }
675
676 if (const MDNode *N = dyn_cast(V)) {
677 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
678 if (Value *Elem = N->getOperand(i))
679 EnumerateOperandType(Elem);
680 }
681 } else if (isa(V) || isa(V))
682 EnumerateMetadata(V);
669 if (auto *MD = dyn_cast(V)) {
670 assert(!isa(MD->getMetadata()) &&
671 "Function-local metadata should be left for later");
672
673 EnumerateMetadata(MD->getMetadata());
674 return;
675 }
676
677 const Constant *C = dyn_cast(V);
678 if (!C)
679 return;
680
681 // If this constant is already enumerated, ignore it, we know its type must
682 // be enumerated.
683 if (ValueMap.count(C))
684 return;
685
686 // This constant may have operands, make sure to enumerate the types in
687 // them.
688 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
689 const Value *Op = C->getOperand(i);
690
691 // Don't enumerate basic blocks here, this happens as operands to
692 // blockaddress.
693 if (isa(Op))
694 continue;
695
696 EnumerateOperandType(Op);
697 }
683698 }
684699
685700 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
707722 void ValueEnumerator::incorporateFunction(const Function &F) {
708723 InstructionCount = 0;
709724 NumModuleValues = Values.size();
710 NumModuleMDValues = MDValues.size();
725 NumModuleMDs = MDs.size();
711726
712727 // Adding function arguments to the value table.
713728 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
738753
739754 FirstInstID = Values.size();
740755
741 SmallVector<MDNode *, 8> FnLocalMDVector;
756 SmallVector<LocalAsMetadata *, 8> FnLocalMDVector;
742757 // Add all of the instructions.
743758 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
744759 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
745760 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
746761 OI != E; ++OI) {
747 if (MDNode *MD = dyn_cast(*OI))
748 if (MD->isFunctionLocal() && MD->getFunction())
762 if (auto *MD = dyn_cast(&*OI))
763 if (auto *Local = dyn_cast(MD->getMetadata()))
749764 // Enumerate metadata after the instructions they might refer to.
750 FnLocalMDVector.push_back(MD);
751 }
752
753 SmallVector, 8> MDs;
754 I->getAllMetadataOtherThanDebugLoc(MDs);
755 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
756 MDNode *N = MDs[i].second;
757 if (N->isFunctionLocal() && N->getFunction())
758 FnLocalMDVector.push_back(N);
765 FnLocalMDVector.push_back(Local);
759766 }
760767
761768 if (!I->getType()->isVoidTy())
772779 /// Remove purged values from the ValueMap.
773780 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
774781 ValueMap.erase(Values[i].first);
775 for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i)
776 MDValueMap.erase(MDValues[i]);
782 for (unsigned i = NumModuleMDs, e = MDs.size(); i != e; ++i)
783 MDValueMap.erase(MDs[i]);
777784 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
778785 ValueMap.erase(BasicBlocks[i]);
779786
780787 Values.resize(NumModuleValues);
781 MDValues.resize(NumModuleMDValues);
788 MDs.resize(NumModuleMDs);
782789 BasicBlocks.clear();
783790 FunctionLocalMDs.clear();
784791 }
2929 class Comdat;
3030 class Function;
3131 class Module;
32 class Metadata;
33 class LocalAsMetadata;
3234 class MDNode;
3335 class NamedMDNode;
3436 class AttributeSet;
5759 typedef UniqueVector ComdatSetType;
5860 ComdatSetType Comdats;
5961
60 std::vector MDValues;
61 SmallVector FunctionLocalMDs;
62 ValueMapType MDValueMap;
62 std::vector MDs;
63 SmallVector FunctionLocalMDs;
64 typedef DenseMap MetadataMapType;
65 MetadataMapType MDValueMap;
6366
6467 typedef DenseMap AttributeGroupMapType;
6568 AttributeGroupMapType AttributeGroupMap;
8790
8891 /// When a function is incorporated, this is the size of the MDValues list
8992 /// before incorporation.
90 unsigned NumModuleMDValues;
93 unsigned NumModuleMDs;
9194
9295 unsigned FirstFuncConstantID;
9396 unsigned FirstInstID;
99102
100103 void dump() const;
101104 void print(raw_ostream &OS, const ValueMapType &Map, const char *Name) const;
105 void print(raw_ostream &OS, const MetadataMapType &Map,
106 const char *Name) const;
102107
103108 unsigned getValueID(const Value *V) const;
109 unsigned getMetadataID(const Metadata *V) const;
104110
105111 unsigned getTypeID(Type *T) const {
106112 TypeMapType::const_iterator I = TypeMap.find(T);
133139 }
134140
135141 const ValueList &getValues() const { return Values; }
136 const std::vector &getMDValues() const { return MDValues; }
137 const SmallVectorImpl &getFunctionLocalMDValues() const {
142 const std::vector &getMDs() const { return MDs; }
143 const SmallVectorImpl &getFunctionLocalMDs() const {
138144 return FunctionLocalMDs;
139145 }
140146 const TypeList &getTypes() const { return Types; }
166172 void OptimizeConstants(unsigned CstStart, unsigned CstEnd);
167173
168174 void EnumerateMDNodeOperands(const MDNode *N);
169 void EnumerateMetadata(const Value *MD);
170 void EnumerateFunctionLocalMetadata(const MDNode *N);
175 void EnumerateMetadata(const Metadata *MD);
176 void EnumerateFunctionLocalMetadata(const LocalAsMetadata *Local);
171177 void EnumerateNamedMDNode(const NamedMDNode *NMD);
172178 void EnumerateValue(const Value *V);
173179 void EnumerateType(Type *T);
6363
6464 if (LocInfo->getNumOperands() != 0)
6565 if (const ConstantInt *CI =
66 dyn_cast(LocInfo->getOperand(ErrorLine)))
66 mdconst::dyn_extract(LocInfo->getOperand(ErrorLine)))
6767 LocCookie = CI->getZExtValue();
6868 }
6969
466466 if (MI->getOperand(i-1).isMetadata() &&
467467 (LocMD = MI->getOperand(i-1).getMetadata()) &&
468468 LocMD->getNumOperands() != 0) {
469 if (const ConstantInt *CI = dyn_cast(LocMD->getOperand(0))) {
469 if (const ConstantInt *CI =
470 mdconst::dyn_extract(LocMD->getOperand(0))) {
470471 LocCookie = CI->getZExtValue();
471472 break;
472473 }
11911191 addType(ParamDIE, resolve(VP.getType()));
11921192 if (!VP.getName().empty())
11931193 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1194 if (Value *Val = VP.getValue()) {
1195 if (ConstantInt *CI = dyn_cast(Val))
1194 if (Metadata *Val = VP.getValue()) {
1195 if (ConstantInt *CI = mdconst::dyn_extract(Val))
11961196 addConstantValue(ParamDIE, CI, resolve(VP.getType()));
1197 else if (GlobalValue *GV = dyn_cast(Val)) {
1197 else if (GlobalValue *GV = mdconst::dyn_extract(Val)) {
11981198 // For declaration non-type template parameters (such as global values and
11991199 // functions)
12001200 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
38093809 if (!ProfileData || ProfileData->getNumOperands() != 3)
38103810 return false;
38113811
3812 const auto *CITrue = dyn_cast(ProfileData->getOperand(1));
3813 const auto *CIFalse = dyn_cast(ProfileData->getOperand(2));
3812 const auto *CITrue =
3813 mdconst::dyn_extract(ProfileData->getOperand(1));
3814 const auto *CIFalse =
3815 mdconst::dyn_extract(ProfileData->getOperand(2));
38143816 if (!CITrue || !CIFalse)
38153817 return false;
38163818
396396 break;
397397 case MachineOperand::MO_Metadata:
398398 OS << '<';
399 getMetadata()->printAsOperand(OS, /*PrintType=*/false);
399 getMetadata()->printAsOperand(OS);
400400 OS << '>';
401401 break;
402402 case MachineOperand::MO_MCSymbol:
536536 if (const MDNode *TBAAInfo = MMO.getAAInfo().TBAA) {
537537 OS << "(tbaa=";
538538 if (TBAAInfo->getNumOperands() > 0)
539 TBAAInfo->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
539 TBAAInfo->getOperand(0)->printAsOperand(OS);
540540 else
541541 OS << "";
542542 OS << ")";
547547 OS << "(alias.scope=";
548548 if (ScopeInfo->getNumOperands() > 0)
549549 for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
550 ScopeInfo->getOperand(i)->printAsOperand(OS, /*PrintType=*/false);
550 ScopeInfo->getOperand(i)->printAsOperand(OS);
551551 if (i != ie-1)
552552 OS << ",";
553553 }
561561 OS << "(noalias=";
562562 if (NoAliasInfo->getNumOperands() > 0)
563563 for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
564 NoAliasInfo->getOperand(i)->printAsOperand(OS, /*PrintType=*/false);
564 NoAliasInfo->getOperand(i)->printAsOperand(OS);
565565 if (i != ie-1)
566566 OS << ",";
567567 }
598598 : MCID(&tid), Parent(nullptr), Operands(nullptr), NumOperands(0),
599599 Flags(0), AsmPrinterFlags(0),
600600 NumMemRefs(0), MemRefs(nullptr), debugLoc(dl) {
601 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
602
601603 // Reserve space for the expected number of operands.
602604 if (unsigned NumOps = MCID->getNumOperands() +
603605 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
616618 Flags(0), AsmPrinterFlags(0),
617619 NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
618620 debugLoc(MI.getDebugLoc()) {
621 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
622
619623 CapOperands = OperandCapacity::get(MI.getNumOperands());
620624 Operands = MF.allocateOperandArray(CapOperands);
621625
19591963 if (getOperand(i-1).isMetadata() &&
19601964 (LocMD = getOperand(i-1).getMetadata()) &&
19611965 LocMD->getNumOperands() != 0) {
1962 if (const ConstantInt *CI = dyn_cast(LocMD->getOperand(0))) {
1966 if (const ConstantInt *CI =
1967 mdconst::dyn_extract(LocMD->getOperand(0))) {
19631968 LocCookie = CI->getZExtValue();
19641969 break;
19651970 }
47134713 return nullptr;
47144714 case Intrinsic::read_register: {
47154715 Value *Reg = I.getArgOperand(0);
4716 SDValue RegName = DAG.getMDNode(cast(Reg));
4716 SDValue RegName =
4717 DAG.getMDNode(cast(cast(Reg)->getMetadata()));
47174718 EVT VT = TLI.getValueType(I.getType());
47184719 setValue(&I, DAG.getNode(ISD::READ_REGISTER, sdl, VT, RegName));
47194720 return nullptr;
47224723 Value *Reg = I.getArgOperand(0);
47234724 Value *RegValue = I.getArgOperand(1);
47244725 SDValue Chain = getValue(RegValue).getOperand(0);
4725 SDValue RegName = DAG.getMDNode(cast(Reg));
4726 SDValue RegName =
4727 DAG.getMDNode(cast(cast(Reg)->getMetadata()));
47264728 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
47274729 RegName, getValue(RegValue)));
47284730 return nullptr;
462462 if (!VI.Var)
463463 continue;
464464 if (SlotRemap.count(VI.Slot)) {
465 DEBUG(dbgs()<<"Remapping debug info for ["<getName()<<"].\n");
465 DEBUG(dbgs() << "Remapping debug info for ["
466 << DIVariable(VI.Var).getName() << "].\n");
466467 VI.Slot = SlotRemap[VI.Slot];
467468 FixedDbg++;
468469 }
463463 continue;
464464
465465 StringRef Key = MFE.Key->getString();
466 Value *Val = MFE.Val;
466 Metadata *Val = MFE.Val;
467467
468468 if (Key == "Objective-C Image Info Version") {
469 VersionVal = cast(Val)->getZExtValue();
469 VersionVal = mdconst::extract(Val)->getZExtValue();
470470 } else if (Key == "Objective-C Garbage Collection" ||
471471 Key == "Objective-C GC Only" ||
472472 Key == "Objective-C Is Simulated" ||
473473 Key == "Objective-C Image Swift Version") {
474 ImageInfoFlags |= cast(Val)->getZExtValue();
474 ImageInfoFlags |= mdconst::extract(Val)->getZExtValue();
475475 } else if (Key == "Objective-C Image Info Section") {
476476 SectionVal = cast(Val)->getString();
477477 } else if (Key == "Linker Options") {
965965 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
966966 const Module::ModuleFlagEntry &MFE = *i;
967967 StringRef Key = MFE.Key->getString();
968 Value *Val = MFE.Val;
968 Metadata *Val = MFE.Val;
969969 if (Key == "Linker Options") {
970970 LinkerOptions = cast(Val);
971971 break;
633633 if (const Function *Func = dyn_cast(V))
634634 return new SlotTracker(Func);
635635
636 if (const MDNode *MD = dyn_cast(V)) {
637 if (!MD->isFunctionLocal())
638 return new SlotTracker(MD->getFunction());
639
640 return new SlotTracker((Function *)nullptr);
641 }
642
643636 return nullptr;
644637 }
645638
652645 // Module level constructor. Causes the contents of the Module (sans functions)
653646 // to be added to the slot table.
654647 SlotTracker::SlotTracker(const Module *M)
655 : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
656 mNext(0), fNext(0), mdnNext(0), asNext(0) {
657 }
648 : TheModule(M), TheFunction(nullptr), FunctionProcessed(false), mNext(0),
649 fNext(0), mdnNext(0), asNext(0) {}
658650
659651 // Function level constructor. Causes the contents of the Module and the one
660652 // function provided to be added to the slot table.
661653 SlotTracker::SlotTracker(const Function *F)
662 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
663 FunctionProcessed(false), mNext(0), fNext(0), mdnNext(0), asNext(0) {
664 }
654 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
655 FunctionProcessed(false), mNext(0), fNext(0), mdnNext(0), asNext(0) {}
665656
666657 inline void SlotTracker::initialize() {
667658 if (TheModule) {
743734 if (Function *F = CI->getCalledFunction())
744735 if (F->isIntrinsic())
745736 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
746 if (MDNode *N = dyn_cast_or_null(I->getOperand(i)))
747 CreateMetadataSlot(N);