xref: /llvm-project/llvm/lib/Bitcode/Reader/ValueList.cpp (revision 8c5a44901cafa5c848d3f2f2c26a23e6583ed657)
1 //===- ValueList.cpp - Internal BitcodeReader implementation --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ValueList.h"
10 #include "llvm/ADT/SmallVector.h"
11 #include "llvm/IR/Argument.h"
12 #include "llvm/IR/Constant.h"
13 #include "llvm/IR/Constants.h"
14 #include "llvm/IR/GlobalValue.h"
15 #include "llvm/IR/Instruction.h"
16 #include "llvm/IR/Type.h"
17 #include "llvm/IR/User.h"
18 #include "llvm/IR/Value.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include <algorithm>
22 #include <cstddef>
23 #include <limits>
24 
25 using namespace llvm;
26 
27 namespace llvm {
28 
29 namespace {
30 
31 /// A class for maintaining the slot number definition
32 /// as a placeholder for the actual definition for forward constants defs.
33 class ConstantPlaceHolder : public ConstantExpr {
34 public:
35   explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
36       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
37     Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
38   }
39 
40   ConstantPlaceHolder &operator=(const ConstantPlaceHolder &) = delete;
41 
42   // allocate space for exactly one operand
43   void *operator new(size_t s) { return User::operator new(s, 1); }
44 
45   /// Methods to support type inquiry through isa, cast, and dyn_cast.
46   static bool classof(const Value *V) {
47     return isa<ConstantExpr>(V) &&
48            cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
49   }
50 
51   /// Provide fast operand accessors
52   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
53 };
54 
55 } // end anonymous namespace
56 
57 // FIXME: can we inherit this from ConstantExpr?
58 template <>
59 struct OperandTraits<ConstantPlaceHolder>
60     : public FixedNumOperandTraits<ConstantPlaceHolder, 1> {};
61 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
62 
63 } // end namespace llvm
64 
65 void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
66   if (Idx == size()) {
67     push_back(V);
68     return;
69   }
70 
71   if (Idx >= size())
72     resize(Idx + 1);
73 
74   WeakTrackingVH &OldV = ValuePtrs[Idx];
75   if (!OldV) {
76     OldV = V;
77     return;
78   }
79 
80   // Handle constants and non-constants (e.g. instrs) differently for
81   // efficiency.
82   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
83     ResolveConstants.push_back(std::make_pair(PHC, Idx));
84     OldV = V;
85   } else {
86     // If there was a forward reference to this value, replace it.
87     Value *PrevVal = OldV;
88     OldV->replaceAllUsesWith(V);
89     PrevVal->deleteValue();
90   }
91 }
92 
93 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, Type *Ty) {
94   // Bail out for a clearly invalid value.
95   if (Idx >= RefsUpperBound)
96     return nullptr;
97 
98   if (Idx >= size())
99     resize(Idx + 1);
100 
101   if (Value *V = ValuePtrs[Idx]) {
102     if (Ty != V->getType()) {
103       Ty->dump();
104       V->getType()->dump();
105       V->dump();
106       report_fatal_error("Type mismatch in constant table!");
107     }
108     return cast<Constant>(V);
109   }
110 
111   // Create and return a placeholder, which will later be RAUW'd.
112   Constant *C = new ConstantPlaceHolder(Ty, Context);
113   ValuePtrs[Idx] = C;
114   return C;
115 }
116 
117 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
118   // Bail out for a clearly invalid value.
119   if (Idx >= RefsUpperBound)
120     return nullptr;
121 
122   if (Idx >= size())
123     resize(Idx + 1);
124 
125   if (Value *V = ValuePtrs[Idx]) {
126     // If the types don't match, it's invalid.
127     if (Ty && Ty != V->getType())
128       return nullptr;
129     return V;
130   }
131 
132   // No type specified, must be invalid reference.
133   if (!Ty)
134     return nullptr;
135 
136   // Create and return a placeholder, which will later be RAUW'd.
137   Value *V = new Argument(Ty);
138   ValuePtrs[Idx] = V;
139   return V;
140 }
141 
142 /// Once all constants are read, this method bulk resolves any forward
143 /// references.  The idea behind this is that we sometimes get constants (such
144 /// as large arrays) which reference *many* forward ref constants.  Replacing
145 /// each of these causes a lot of thrashing when building/reuniquing the
146 /// constant.  Instead of doing this, we look at all the uses and rewrite all
147 /// the place holders at once for any constant that uses a placeholder.
148 void BitcodeReaderValueList::resolveConstantForwardRefs() {
149   // Sort the values by-pointer so that they are efficient to look up with a
150   // binary search.
151   llvm::sort(ResolveConstants);
152 
153   SmallVector<Constant *, 64> NewOps;
154 
155   while (!ResolveConstants.empty()) {
156     Value *RealVal = operator[](ResolveConstants.back().second);
157     Constant *Placeholder = ResolveConstants.back().first;
158     ResolveConstants.pop_back();
159 
160     // Loop over all users of the placeholder, updating them to reference the
161     // new value.  If they reference more than one placeholder, update them all
162     // at once.
163     while (!Placeholder->use_empty()) {
164       auto UI = Placeholder->user_begin();
165       User *U = *UI;
166 
167       // If the using object isn't uniqued, just update the operands.  This
168       // handles instructions and initializers for global variables.
169       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
170         UI.getUse().set(RealVal);
171         continue;
172       }
173 
174       // Otherwise, we have a constant that uses the placeholder.  Replace that
175       // constant with a new constant that has *all* placeholder uses updated.
176       Constant *UserC = cast<Constant>(U);
177       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); I != E;
178            ++I) {
179         Value *NewOp;
180         if (!isa<ConstantPlaceHolder>(*I)) {
181           // Not a placeholder reference.
182           NewOp = *I;
183         } else if (*I == Placeholder) {
184           // Common case is that it just references this one placeholder.
185           NewOp = RealVal;
186         } else {
187           // Otherwise, look up the placeholder in ResolveConstants.
188           ResolveConstantsTy::iterator It = llvm::lower_bound(
189               ResolveConstants,
190               std::pair<Constant *, unsigned>(cast<Constant>(*I), 0));
191           assert(It != ResolveConstants.end() && It->first == *I);
192           NewOp = operator[](It->second);
193         }
194 
195         NewOps.push_back(cast<Constant>(NewOp));
196       }
197 
198       // Make the new constant.
199       Constant *NewC;
200       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
201         NewC = ConstantArray::get(UserCA->getType(), NewOps);
202       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
203         NewC = ConstantStruct::get(UserCS->getType(), NewOps);
204       } else if (isa<ConstantVector>(UserC)) {
205         NewC = ConstantVector::get(NewOps);
206       } else {
207         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
208         NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
209       }
210 
211       UserC->replaceAllUsesWith(NewC);
212       UserC->destroyConstant();
213       NewOps.clear();
214     }
215 
216     // Update all ValueHandles, they should be the only users at this point.
217     Placeholder->replaceAllUsesWith(RealVal);
218     delete cast<ConstantPlaceHolder>(Placeholder);
219   }
220 }
221