Bug Summary

File:lib/Transforms/Scalar/SCCP.cpp
Warning:line 483, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SCCP.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/lib/Transforms/Scalar -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp

1//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements sparse conditional constant propagation and merging:
11//
12// Specifically, this:
13// * Assumes values are constant unless proven otherwise
14// * Assumes BasicBlocks are dead unless proven otherwise
15// * Proves values to be constant, and replaces them with constants
16// * Proves conditional branches to be unconditional
17//
18//===----------------------------------------------------------------------===//
19
20#include "llvm/Transforms/Scalar/SCCP.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/DenseSet.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/Analysis/ConstantFolding.h"
30#include "llvm/Analysis/GlobalsModRef.h"
31#include "llvm/Analysis/TargetLibraryInfo.h"
32#include "llvm/Transforms/Utils/Local.h"
33#include "llvm/Analysis/ValueLattice.h"
34#include "llvm/Analysis/ValueLatticeUtils.h"
35#include "llvm/IR/BasicBlock.h"
36#include "llvm/IR/CallSite.h"
37#include "llvm/IR/Constant.h"
38#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/DerivedTypes.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/GlobalVariable.h"
43#include "llvm/IR/InstVisitor.h"
44#include "llvm/IR/InstrTypes.h"
45#include "llvm/IR/Instruction.h"
46#include "llvm/IR/Instructions.h"
47#include "llvm/IR/Module.h"
48#include "llvm/IR/PassManager.h"
49#include "llvm/IR/Type.h"
50#include "llvm/IR/User.h"
51#include "llvm/IR/Value.h"
52#include "llvm/Pass.h"
53#include "llvm/Support/Casting.h"
54#include "llvm/Support/Debug.h"
55#include "llvm/Support/ErrorHandling.h"
56#include "llvm/Support/raw_ostream.h"
57#include "llvm/Transforms/Scalar.h"
58#include "llvm/Transforms/Utils/PredicateInfo.h"
59#include <cassert>
60#include <utility>
61#include <vector>
62
63using namespace llvm;
64
65#define DEBUG_TYPE"sccp" "sccp"
66
67STATISTIC(NumInstRemoved, "Number of instructions removed")static llvm::Statistic NumInstRemoved = {"sccp", "NumInstRemoved"
, "Number of instructions removed", {0}, {false}}
;
68STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable")static llvm::Statistic NumDeadBlocks = {"sccp", "NumDeadBlocks"
, "Number of basic blocks unreachable", {0}, {false}}
;
69
70STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP")static llvm::Statistic IPNumInstRemoved = {"sccp", "IPNumInstRemoved"
, "Number of instructions removed by IPSCCP", {0}, {false}}
;
71STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP")static llvm::Statistic IPNumArgsElimed = {"sccp", "IPNumArgsElimed"
, "Number of arguments constant propagated by IPSCCP", {0}, {
false}}
;
72STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP")static llvm::Statistic IPNumGlobalConst = {"sccp", "IPNumGlobalConst"
, "Number of globals found to be constant by IPSCCP", {0}, {false
}}
;
73
74namespace {
75
76/// LatticeVal class - This class represents the different lattice values that
77/// an LLVM value may occupy. It is a simple class with value semantics.
78///
79class LatticeVal {
80 enum LatticeValueTy {
81 /// unknown - This LLVM Value has no known value yet.
82 unknown,
83
84 /// constant - This LLVM Value has a specific constant value.
85 constant,
86
87 /// forcedconstant - This LLVM Value was thought to be undef until
88 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
89 /// with another (different) constant, it goes to overdefined, instead of
90 /// asserting.
91 forcedconstant,
92
93 /// overdefined - This instruction is not known to be constant, and we know
94 /// it has a value.
95 overdefined
96 };
97
98 /// Val: This stores the current lattice value along with the Constant* for
99 /// the constant if this is a 'constant' or 'forcedconstant' value.
100 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
101
102 LatticeValueTy getLatticeValue() const {
103 return Val.getInt();
104 }
105
106public:
107 LatticeVal() : Val(nullptr, unknown) {}
108
109 bool isUnknown() const { return getLatticeValue() == unknown; }
110
111 bool isConstant() const {
112 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
113 }
114
115 bool isOverdefined() const { return getLatticeValue() == overdefined; }
116
117 Constant *getConstant() const {
118 assert(isConstant() && "Cannot get the constant of a non-constant!")((isConstant() && "Cannot get the constant of a non-constant!"
) ? static_cast<void> (0) : __assert_fail ("isConstant() && \"Cannot get the constant of a non-constant!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 118, __PRETTY_FUNCTION__))
;
119 return Val.getPointer();
120 }
121
122 /// markOverdefined - Return true if this is a change in status.
123 bool markOverdefined() {
124 if (isOverdefined())
125 return false;
126
127 Val.setInt(overdefined);
128 return true;
129 }
130
131 /// markConstant - Return true if this is a change in status.
132 bool markConstant(Constant *V) {
133 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
134 assert(getConstant() == V && "Marking constant with different value")((getConstant() == V && "Marking constant with different value"
) ? static_cast<void> (0) : __assert_fail ("getConstant() == V && \"Marking constant with different value\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 134, __PRETTY_FUNCTION__))
;
135 return false;
136 }
137
138 if (isUnknown()) {
139 Val.setInt(constant);
140 assert(V && "Marking constant with NULL")((V && "Marking constant with NULL") ? static_cast<
void> (0) : __assert_fail ("V && \"Marking constant with NULL\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 140, __PRETTY_FUNCTION__))
;
141 Val.setPointer(V);
142 } else {
143 assert(getLatticeValue() == forcedconstant &&((getLatticeValue() == forcedconstant && "Cannot move from overdefined to constant!"
) ? static_cast<void> (0) : __assert_fail ("getLatticeValue() == forcedconstant && \"Cannot move from overdefined to constant!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 144, __PRETTY_FUNCTION__))
144 "Cannot move from overdefined to constant!")((getLatticeValue() == forcedconstant && "Cannot move from overdefined to constant!"
) ? static_cast<void> (0) : __assert_fail ("getLatticeValue() == forcedconstant && \"Cannot move from overdefined to constant!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 144, __PRETTY_FUNCTION__))
;
145 // Stay at forcedconstant if the constant is the same.
146 if (V == getConstant()) return false;
147
148 // Otherwise, we go to overdefined. Assumptions made based on the
149 // forced value are possibly wrong. Assuming this is another constant
150 // could expose a contradiction.
151 Val.setInt(overdefined);
152 }
153 return true;
154 }
155
156 /// getConstantInt - If this is a constant with a ConstantInt value, return it
157 /// otherwise return null.
158 ConstantInt *getConstantInt() const {
159 if (isConstant())
160 return dyn_cast<ConstantInt>(getConstant());
161 return nullptr;
162 }
163
164 /// getBlockAddress - If this is a constant with a BlockAddress value, return
165 /// it, otherwise return null.
166 BlockAddress *getBlockAddress() const {
167 if (isConstant())
168 return dyn_cast<BlockAddress>(getConstant());
169 return nullptr;
170 }
171
172 void markForcedConstant(Constant *V) {
173 assert(isUnknown() && "Can't force a defined value!")((isUnknown() && "Can't force a defined value!") ? static_cast
<void> (0) : __assert_fail ("isUnknown() && \"Can't force a defined value!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 173, __PRETTY_FUNCTION__))
;
174 Val.setInt(forcedconstant);
175 Val.setPointer(V);
176 }
177
178 ValueLatticeElement toValueLattice() const {
179 if (isOverdefined())
180 return ValueLatticeElement::getOverdefined();
181 if (isConstant())
182 return ValueLatticeElement::get(getConstant());
183 return ValueLatticeElement();
184 }
185};
186
187//===----------------------------------------------------------------------===//
188//
189/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
190/// Constant Propagation.
191///
192class SCCPSolver : public InstVisitor<SCCPSolver> {
193 const DataLayout &DL;
194 const TargetLibraryInfo *TLI;
195 SmallPtrSet<BasicBlock *, 8> BBExecutable; // The BBs that are executable.
196 DenseMap<Value *, LatticeVal> ValueState; // The state each value is in.
197 // The state each parameter is in.
198 DenseMap<Value *, ValueLatticeElement> ParamState;
199
200 /// StructValueState - This maintains ValueState for values that have
201 /// StructType, for example for formal arguments, calls, insertelement, etc.
202 DenseMap<std::pair<Value *, unsigned>, LatticeVal> StructValueState;
203
204 /// GlobalValue - If we are tracking any values for the contents of a global
205 /// variable, we keep a mapping from the constant accessor to the element of
206 /// the global, to the currently known value. If the value becomes
207 /// overdefined, it's entry is simply removed from this map.
208 DenseMap<GlobalVariable *, LatticeVal> TrackedGlobals;
209
210 /// TrackedRetVals - If we are tracking arguments into and the return
211 /// value out of a function, it will have an entry in this map, indicating
212 /// what the known return value for the function is.
213 DenseMap<Function *, LatticeVal> TrackedRetVals;
214
215 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
216 /// that return multiple values.
217 DenseMap<std::pair<Function *, unsigned>, LatticeVal> TrackedMultipleRetVals;
218
219 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
220 /// represented here for efficient lookup.
221 SmallPtrSet<Function *, 16> MRVFunctionsTracked;
222
223 /// MustTailFunctions - Each function here is a callee of non-removable
224 /// musttail call site.
225 SmallPtrSet<Function *, 16> MustTailCallees;
226
227 /// TrackingIncomingArguments - This is the set of functions for whose
228 /// arguments we make optimistic assumptions about and try to prove as
229 /// constants.
230 SmallPtrSet<Function *, 16> TrackingIncomingArguments;
231
232 /// The reason for two worklists is that overdefined is the lowest state
233 /// on the lattice, and moving things to overdefined as fast as possible
234 /// makes SCCP converge much faster.
235 ///
236 /// By having a separate worklist, we accomplish this because everything
237 /// possibly overdefined will become overdefined at the soonest possible
238 /// point.
239 SmallVector<Value *, 64> OverdefinedInstWorkList;
240 SmallVector<Value *, 64> InstWorkList;
241
242 // The BasicBlock work list
243 SmallVector<BasicBlock *, 64> BBWorkList;
244
245 /// KnownFeasibleEdges - Entries in this set are edges which have already had
246 /// PHI nodes retriggered.
247 using Edge = std::pair<BasicBlock *, BasicBlock *>;
248 DenseSet<Edge> KnownFeasibleEdges;
249
250 DenseMap<Function *, std::unique_ptr<PredicateInfo>> PredInfos;
251 DenseMap<Value *, SmallPtrSet<User *, 2>> AdditionalUsers;
252
253public:
254 void addPredInfo(Function &F, std::unique_ptr<PredicateInfo> PI) {
255 PredInfos[&F] = std::move(PI);
256 }
257
258 const PredicateBase *getPredicateInfoFor(Instruction *I) {
259 auto PI = PredInfos.find(I->getFunction());
260 if (PI == PredInfos.end())
261 return nullptr;
262 return PI->second->getPredicateInfoFor(I);
263 }
264
265 SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli)
266 : DL(DL), TLI(tli) {}
267
268 /// MarkBlockExecutable - This method can be used by clients to mark all of
269 /// the blocks that are known to be intrinsically live in the processed unit.
270 ///
271 /// This returns true if the block was not considered live before.
272 bool MarkBlockExecutable(BasicBlock *BB) {
273 if (!BBExecutable.insert(BB).second)
274 return false;
275 LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "Marking Block Executable: " <<
BB->getName() << '\n'; } } while (false)
;
276 BBWorkList.push_back(BB); // Add the block to the work list!
277 return true;
278 }
279
280 /// TrackValueOfGlobalVariable - Clients can use this method to
281 /// inform the SCCPSolver that it should track loads and stores to the
282 /// specified global variable if it can. This is only legal to call if
283 /// performing Interprocedural SCCP.
284 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
285 // We only track the contents of scalar globals.
286 if (GV->getValueType()->isSingleValueType()) {
287 LatticeVal &IV = TrackedGlobals[GV];
288 if (!isa<UndefValue>(GV->getInitializer()))
289 IV.markConstant(GV->getInitializer());
290 }
291 }
292
293 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
294 /// and out of the specified function (which cannot have its address taken),
295 /// this method must be called.
296 void AddTrackedFunction(Function *F) {
297 // Add an entry, F -> undef.
298 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
299 MRVFunctionsTracked.insert(F);
300 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
301 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
302 LatticeVal()));
303 } else
304 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
305 }
306
307 /// AddMustTailCallee - If the SCCP solver finds that this function is called
308 /// from non-removable musttail call site.
309 void AddMustTailCallee(Function *F) {
310 MustTailCallees.insert(F);
311 }
312
313 /// Returns true if the given function is called from non-removable musttail
314 /// call site.
315 bool isMustTailCallee(Function *F) {
316 return MustTailCallees.count(F);
317 }
318
319 void AddArgumentTrackedFunction(Function *F) {
320 TrackingIncomingArguments.insert(F);
321 }
322
323 /// Returns true if the given function is in the solver's set of
324 /// argument-tracked functions.
325 bool isArgumentTrackedFunction(Function *F) {
326 return TrackingIncomingArguments.count(F);
327 }
328
329 /// Solve - Solve for constants and executable blocks.
330 void Solve();
331
332 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
333 /// that branches on undef values cannot reach any of their successors.
334 /// However, this is not a safe assumption. After we solve dataflow, this
335 /// method should be use to handle this. If this returns true, the solver
336 /// should be rerun.
337 bool ResolvedUndefsIn(Function &F);
338
339 bool isBlockExecutable(BasicBlock *BB) const {
340 return BBExecutable.count(BB);
341 }
342
343 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
344 // block to the 'To' basic block is currently feasible.
345 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
346
347 std::vector<LatticeVal> getStructLatticeValueFor(Value *V) const {
348 std::vector<LatticeVal> StructValues;
349 auto *STy = dyn_cast<StructType>(V->getType());
350 assert(STy && "getStructLatticeValueFor() can be called only on structs")((STy && "getStructLatticeValueFor() can be called only on structs"
) ? static_cast<void> (0) : __assert_fail ("STy && \"getStructLatticeValueFor() can be called only on structs\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 350, __PRETTY_FUNCTION__))
;
351 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
352 auto I = StructValueState.find(std::make_pair(V, i));
353 assert(I != StructValueState.end() && "Value not in valuemap!")((I != StructValueState.end() && "Value not in valuemap!"
) ? static_cast<void> (0) : __assert_fail ("I != StructValueState.end() && \"Value not in valuemap!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 353, __PRETTY_FUNCTION__))
;
354 StructValues.push_back(I->second);
355 }
356 return StructValues;
357 }
358
359 const LatticeVal &getLatticeValueFor(Value *V) const {
360 assert(!V->getType()->isStructTy() &&((!V->getType()->isStructTy() && "Should use getStructLatticeValueFor"
) ? static_cast<void> (0) : __assert_fail ("!V->getType()->isStructTy() && \"Should use getStructLatticeValueFor\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 361, __PRETTY_FUNCTION__))
361 "Should use getStructLatticeValueFor")((!V->getType()->isStructTy() && "Should use getStructLatticeValueFor"
) ? static_cast<void> (0) : __assert_fail ("!V->getType()->isStructTy() && \"Should use getStructLatticeValueFor\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 361, __PRETTY_FUNCTION__))
;
362 DenseMap<Value *, LatticeVal>::const_iterator I = ValueState.find(V);
363 assert(I != ValueState.end() &&((I != ValueState.end() && "V not found in ValueState nor Paramstate map!"
) ? static_cast<void> (0) : __assert_fail ("I != ValueState.end() && \"V not found in ValueState nor Paramstate map!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 364, __PRETTY_FUNCTION__))
364 "V not found in ValueState nor Paramstate map!")((I != ValueState.end() && "V not found in ValueState nor Paramstate map!"
) ? static_cast<void> (0) : __assert_fail ("I != ValueState.end() && \"V not found in ValueState nor Paramstate map!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 364, __PRETTY_FUNCTION__))
;
365 return I->second;
366 }
367
368 /// getTrackedRetVals - Get the inferred return value map.
369 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
370 return TrackedRetVals;
371 }
372
373 /// getTrackedGlobals - Get and return the set of inferred initializers for
374 /// global variables.
375 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
376 return TrackedGlobals;
377 }
378
379 /// getMRVFunctionsTracked - Get the set of functions which return multiple
380 /// values tracked by the pass.
381 const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
382 return MRVFunctionsTracked;
383 }
384
385 /// getMustTailCallees - Get the set of functions which are called
386 /// from non-removable musttail call sites.
387 const SmallPtrSet<Function *, 16> getMustTailCallees() {
388 return MustTailCallees;
389 }
390
391 /// markOverdefined - Mark the specified value overdefined. This
392 /// works with both scalars and structs.
393 void markOverdefined(Value *V) {
394 if (auto *STy = dyn_cast<StructType>(V->getType()))
395 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
396 markOverdefined(getStructValueState(V, i), V);
397 else
398 markOverdefined(ValueState[V], V);
399 }
400
401 // isStructLatticeConstant - Return true if all the lattice values
402 // corresponding to elements of the structure are not overdefined,
403 // false otherwise.
404 bool isStructLatticeConstant(Function *F, StructType *STy) {
405 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
406 const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
407 assert(It != TrackedMultipleRetVals.end())((It != TrackedMultipleRetVals.end()) ? static_cast<void>
(0) : __assert_fail ("It != TrackedMultipleRetVals.end()", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 407, __PRETTY_FUNCTION__))
;
408 LatticeVal LV = It->second;
409 if (LV.isOverdefined())
410 return false;
411 }
412 return true;
413 }
414
415private:
416 // pushToWorkList - Helper for markConstant/markForcedConstant/markOverdefined
417 void pushToWorkList(LatticeVal &IV, Value *V) {
418 if (IV.isOverdefined())
419 return OverdefinedInstWorkList.push_back(V);
420 InstWorkList.push_back(V);
421 }
422
423 // markConstant - Make a value be marked as "constant". If the value
424 // is not already a constant, add it to the instruction work list so that
425 // the users of the instruction are updated later.
426 bool markConstant(LatticeVal &IV, Value *V, Constant *C) {
427 if (!IV.markConstant(C)) return false;
428 LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "markConstant: " << *C <<
": " << *V << '\n'; } } while (false)
;
429 pushToWorkList(IV, V);
430 return true;
431 }
432
433 bool markConstant(Value *V, Constant *C) {
434 assert(!V->getType()->isStructTy() && "structs should use mergeInValue")((!V->getType()->isStructTy() && "structs should use mergeInValue"
) ? static_cast<void> (0) : __assert_fail ("!V->getType()->isStructTy() && \"structs should use mergeInValue\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 434, __PRETTY_FUNCTION__))
;
435 return markConstant(ValueState[V], V, C);
436 }
437
438 void markForcedConstant(Value *V, Constant *C) {
439 assert(!V->getType()->isStructTy() && "structs should use mergeInValue")((!V->getType()->isStructTy() && "structs should use mergeInValue"
) ? static_cast<void> (0) : __assert_fail ("!V->getType()->isStructTy() && \"structs should use mergeInValue\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 439, __PRETTY_FUNCTION__))
;
440 LatticeVal &IV = ValueState[V];
441 IV.markForcedConstant(C);
442 LLVM_DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "markForcedConstant: " << *
C << ": " << *V << '\n'; } } while (false)
;
443 pushToWorkList(IV, V);
444 }
445
446 // markOverdefined - Make a value be marked as "overdefined". If the
447 // value is not already overdefined, add it to the overdefined instruction
448 // work list so that the users of the instruction are updated later.
449 bool markOverdefined(LatticeVal &IV, Value *V) {
450 if (!IV.markOverdefined()) return false;
451
452 LLVM_DEBUG(dbgs() << "markOverdefined: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "markOverdefined: "; if (auto *F =
dyn_cast<Function>(V)) dbgs() << "Function '" <<
F->getName() << "'\n"; else dbgs() << *V <<
'\n'; } } while (false)
453 if (auto *F = dyn_cast<Function>(V)) dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "markOverdefined: "; if (auto *F =
dyn_cast<Function>(V)) dbgs() << "Function '" <<
F->getName() << "'\n"; else dbgs() << *V <<
'\n'; } } while (false)
454 << "Function '" << F->getName() << "'\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "markOverdefined: "; if (auto *F =
dyn_cast<Function>(V)) dbgs() << "Function '" <<
F->getName() << "'\n"; else dbgs() << *V <<
'\n'; } } while (false)
455 else dbgs() << *V << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "markOverdefined: "; if (auto *F =
dyn_cast<Function>(V)) dbgs() << "Function '" <<
F->getName() << "'\n"; else dbgs() << *V <<
'\n'; } } while (false)
;
456 // Only instructions go on the work list
457 pushToWorkList(IV, V);
458 return true;
459 }
460
461 bool mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
462 if (IV.isOverdefined() || MergeWithV.isUnknown())
463 return false; // Noop.
464 if (MergeWithV.isOverdefined())
465 return markOverdefined(IV, V);
466 if (IV.isUnknown())
467 return markConstant(IV, V, MergeWithV.getConstant());
468 if (IV.getConstant() != MergeWithV.getConstant())
469 return markOverdefined(IV, V);
470 return false;
471 }
472
473 bool mergeInValue(Value *V, LatticeVal MergeWithV) {
474 assert(!V->getType()->isStructTy() &&((!V->getType()->isStructTy() && "non-structs should use markConstant"
) ? static_cast<void> (0) : __assert_fail ("!V->getType()->isStructTy() && \"non-structs should use markConstant\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 475, __PRETTY_FUNCTION__))
475 "non-structs should use markConstant")((!V->getType()->isStructTy() && "non-structs should use markConstant"
) ? static_cast<void> (0) : __assert_fail ("!V->getType()->isStructTy() && \"non-structs should use markConstant\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 475, __PRETTY_FUNCTION__))
;
476 return mergeInValue(ValueState[V], V, MergeWithV);
477 }
478
479 /// getValueState - Return the LatticeVal object that corresponds to the
480 /// value. This function handles the case when the value hasn't been seen yet
481 /// by properly seeding constants etc.
482 LatticeVal &getValueState(Value *V) {
483 assert(!V->getType()->isStructTy() && "Should use getStructValueState")((!V->getType()->isStructTy() && "Should use getStructValueState"
) ? static_cast<void> (0) : __assert_fail ("!V->getType()->isStructTy() && \"Should use getStructValueState\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 483, __PRETTY_FUNCTION__))
;
24
Within the expansion of the macro 'assert':
a
Called C++ object pointer is null
484
485 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
486 ValueState.insert(std::make_pair(V, LatticeVal()));
487 LatticeVal &LV = I.first->second;
488
489 if (!I.second)
490 return LV; // Common case, already in the map.
491
492 if (auto *C = dyn_cast<Constant>(V)) {
493 // Undef values remain unknown.
494 if (!isa<UndefValue>(V))
495 LV.markConstant(C); // Constants are constant
496 }
497
498 // All others are underdefined by default.
499 return LV;
500 }
501
502 ValueLatticeElement &getParamState(Value *V) {
503 assert(!V->getType()->isStructTy() && "Should use getStructValueState")((!V->getType()->isStructTy() && "Should use getStructValueState"
) ? static_cast<void> (0) : __assert_fail ("!V->getType()->isStructTy() && \"Should use getStructValueState\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 503, __PRETTY_FUNCTION__))
;
504
505 std::pair<DenseMap<Value*, ValueLatticeElement>::iterator, bool>
506 PI = ParamState.insert(std::make_pair(V, ValueLatticeElement()));
507 ValueLatticeElement &LV = PI.first->second;
508 if (PI.second)
509 LV = getValueState(V).toValueLattice();
510
511 return LV;
512 }
513
514 /// getStructValueState - Return the LatticeVal object that corresponds to the
515 /// value/field pair. This function handles the case when the value hasn't
516 /// been seen yet by properly seeding constants etc.
517 LatticeVal &getStructValueState(Value *V, unsigned i) {
518 assert(V->getType()->isStructTy() && "Should use getValueState")((V->getType()->isStructTy() && "Should use getValueState"
) ? static_cast<void> (0) : __assert_fail ("V->getType()->isStructTy() && \"Should use getValueState\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 518, __PRETTY_FUNCTION__))
;
519 assert(i < cast<StructType>(V->getType())->getNumElements() &&((i < cast<StructType>(V->getType())->getNumElements
() && "Invalid element #") ? static_cast<void> (
0) : __assert_fail ("i < cast<StructType>(V->getType())->getNumElements() && \"Invalid element #\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 520, __PRETTY_FUNCTION__))
520 "Invalid element #")((i < cast<StructType>(V->getType())->getNumElements
() && "Invalid element #") ? static_cast<void> (
0) : __assert_fail ("i < cast<StructType>(V->getType())->getNumElements() && \"Invalid element #\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 520, __PRETTY_FUNCTION__))
;
521
522 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
523 bool> I = StructValueState.insert(
524 std::make_pair(std::make_pair(V, i), LatticeVal()));
525 LatticeVal &LV = I.first->second;
526
527 if (!I.second)
528 return LV; // Common case, already in the map.
529
530 if (auto *C = dyn_cast<Constant>(V)) {
531 Constant *Elt = C->getAggregateElement(i);
532
533 if (!Elt)
534 LV.markOverdefined(); // Unknown sort of constant.
535 else if (isa<UndefValue>(Elt))
536 ; // Undef values remain unknown.
537 else
538 LV.markConstant(Elt); // Constants are constant.
539 }
540
541 // All others are underdefined by default.
542 return LV;
543 }
544
545 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
546 /// work list if it is not already executable.
547 bool markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
548 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
549 return false; // This edge is already known to be executable!
550
551 if (!MarkBlockExecutable(Dest)) {
552 // If the destination is already executable, we just made an *edge*
553 // feasible that wasn't before. Revisit the PHI nodes in the block
554 // because they have potentially new operands.
555 LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "Marking Edge Executable: " <<
Source->getName() << " -> " << Dest->getName
() << '\n'; } } while (false)
556 << " -> " << Dest->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "Marking Edge Executable: " <<
Source->getName() << " -> " << Dest->getName
() << '\n'; } } while (false)
;
557
558 for (PHINode &PN : Dest->phis())
559 visitPHINode(PN);
560 }
561 return true;
562 }
563
564 // getFeasibleSuccessors - Return a vector of booleans to indicate which
565 // successors are reachable from a given terminator instruction.
566 void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl<bool> &Succs);
567
568 // OperandChangedState - This method is invoked on all of the users of an
569 // instruction that was just changed state somehow. Based on this
570 // information, we need to update the specified user of this instruction.
571 void OperandChangedState(Instruction *I) {
572 if (BBExecutable.count(I->getParent())) // Inst is executable?
573 visit(*I);
574 }
575
576 // Add U as additional user of V.
577 void addAdditionalUser(Value *V, User *U) {
578 auto Iter = AdditionalUsers.insert({V, {}});
579 Iter.first->second.insert(U);
580 }
581
582 // Mark I's users as changed, including AdditionalUsers.
583 void markUsersAsChanged(Value *I) {
584 for (User *U : I->users())
585 if (auto *UI = dyn_cast<Instruction>(U))
586 OperandChangedState(UI);
587
588 auto Iter = AdditionalUsers.find(I);
589 if (Iter != AdditionalUsers.end()) {
590 for (User *U : Iter->second)
591 if (auto *UI = dyn_cast<Instruction>(U))
592 OperandChangedState(UI);
593 }
594 }
595
596private:
597 friend class InstVisitor<SCCPSolver>;
598
599 // visit implementations - Something changed in this instruction. Either an
600 // operand made a transition, or the instruction is newly executable. Change
601 // the value type of I to reflect these changes if appropriate.
602 void visitPHINode(PHINode &I);
603
604 // Terminators
605
606 void visitReturnInst(ReturnInst &I);
607 void visitTerminator(Instruction &TI);
608
609 void visitCastInst(CastInst &I);
610 void visitSelectInst(SelectInst &I);
611 void visitBinaryOperator(Instruction &I);
612 void visitCmpInst(CmpInst &I);
613 void visitExtractValueInst(ExtractValueInst &EVI);
614 void visitInsertValueInst(InsertValueInst &IVI);
615
616 void visitCatchSwitchInst(CatchSwitchInst &CPI) {
617 markOverdefined(&CPI);
618 visitTerminator(CPI);
619 }
620
621 // Instructions that cannot be folded away.
622
623 void visitStoreInst (StoreInst &I);
624 void visitLoadInst (LoadInst &I);
625 void visitGetElementPtrInst(GetElementPtrInst &I);
626
627 void visitCallInst (CallInst &I) {
628 visitCallSite(&I);
1
Calling 'SCCPSolver::visitCallSite'
629 }
630
631 void visitInvokeInst (InvokeInst &II) {
632 visitCallSite(&II);
633 visitTerminator(II);
634 }
635
636 void visitCallSite (CallSite CS);
637 void visitResumeInst (ResumeInst &I) { /*returns void*/ }
638 void visitUnreachableInst(UnreachableInst &I) { /*returns void*/ }
639 void visitFenceInst (FenceInst &I) { /*returns void*/ }
640
641 void visitInstruction(Instruction &I) {
642 // All the instructions we don't do any special handling for just
643 // go to overdefined.
644 LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "SCCP: Don't know how to handle: "
<< I << '\n'; } } while (false)
;
645 markOverdefined(&I);
646 }
647};
648
649} // end anonymous namespace
650
651// getFeasibleSuccessors - Return a vector of booleans to indicate which
652// successors are reachable from a given terminator instruction.
653void SCCPSolver::getFeasibleSuccessors(Instruction &TI,
654 SmallVectorImpl<bool> &Succs) {
655 Succs.resize(TI.getNumSuccessors());
656 if (auto *BI = dyn_cast<BranchInst>(&TI)) {
657 if (BI->isUnconditional()) {
658 Succs[0] = true;
659 return;
660 }
661
662 LatticeVal BCValue = getValueState(BI->getCondition());
663 ConstantInt *CI = BCValue.getConstantInt();
664 if (!CI) {
665 // Overdefined condition variables, and branches on unfoldable constant
666 // conditions, mean the branch could go either way.
667 if (!BCValue.isUnknown())
668 Succs[0] = Succs[1] = true;
669 return;
670 }
671
672 // Constant condition variables mean the branch can only go a single way.
673 Succs[CI->isZero()] = true;
674 return;
675 }
676
677 // Unwinding instructions successors are always executable.
678 if (TI.isExceptionalTerminator()) {
679 Succs.assign(TI.getNumSuccessors(), true);
680 return;
681 }
682
683 if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
684 if (!SI->getNumCases()) {
685 Succs[0] = true;
686 return;
687 }
688 LatticeVal SCValue = getValueState(SI->getCondition());
689 ConstantInt *CI = SCValue.getConstantInt();
690
691 if (!CI) { // Overdefined or unknown condition?
692 // All destinations are executable!
693 if (!SCValue.isUnknown())
694 Succs.assign(TI.getNumSuccessors(), true);
695 return;
696 }
697
698 Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
699 return;
700 }
701
702 // In case of indirect branch and its address is a blockaddress, we mark
703 // the target as executable.
704 if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
705 // Casts are folded by visitCastInst.
706 LatticeVal IBRValue = getValueState(IBR->getAddress());
707 BlockAddress *Addr = IBRValue.getBlockAddress();
708 if (!Addr) { // Overdefined or unknown condition?
709 // All destinations are executable!
710 if (!IBRValue.isUnknown())
711 Succs.assign(TI.getNumSuccessors(), true);
712 return;
713 }
714
715 BasicBlock* T = Addr->getBasicBlock();
716 assert(Addr->getFunction() == T->getParent() &&((Addr->getFunction() == T->getParent() && "Block address of a different function ?"
) ? static_cast<void> (0) : __assert_fail ("Addr->getFunction() == T->getParent() && \"Block address of a different function ?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 717, __PRETTY_FUNCTION__))
717 "Block address of a different function ?")((Addr->getFunction() == T->getParent() && "Block address of a different function ?"
) ? static_cast<void> (0) : __assert_fail ("Addr->getFunction() == T->getParent() && \"Block address of a different function ?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 717, __PRETTY_FUNCTION__))
;
718 for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
719 // This is the target.
720 if (IBR->getDestination(i) == T) {
721 Succs[i] = true;
722 return;
723 }
724 }
725
726 // If we didn't find our destination in the IBR successor list, then we
727 // have undefined behavior. Its ok to assume no successor is executable.
728 return;
729 }
730
731 LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "Unknown terminator instruction: "
<< TI << '\n'; } } while (false)
;
732 llvm_unreachable("SCCP: Don't know how to handle this terminator!")::llvm::llvm_unreachable_internal("SCCP: Don't know how to handle this terminator!"
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 732)
;
733}
734
735// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
736// block to the 'To' basic block is currently feasible.
737bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
738 // Check if we've called markEdgeExecutable on the edge yet. (We could
739 // be more aggressive and try to consider edges which haven't been marked
740 // yet, but there isn't any need.)
741 return KnownFeasibleEdges.count(Edge(From, To));
742}
743
744// visit Implementations - Something changed in this instruction, either an
745// operand made a transition, or the instruction is newly executable. Change
746// the value type of I to reflect these changes if appropriate. This method
747// makes sure to do the following actions:
748//
749// 1. If a phi node merges two constants in, and has conflicting value coming
750// from different branches, or if the PHI node merges in an overdefined
751// value, then the PHI node becomes overdefined.
752// 2. If a phi node merges only constants in, and they all agree on value, the
753// PHI node becomes a constant value equal to that.
754// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
755// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
756// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
757// 6. If a conditional branch has a value that is constant, make the selected
758// destination executable
759// 7. If a conditional branch has a value that is overdefined, make all
760// successors executable.
761void SCCPSolver::visitPHINode(PHINode &PN) {
762 // If this PN returns a struct, just mark the result overdefined.
763 // TODO: We could do a lot better than this if code actually uses this.
764 if (PN.getType()->isStructTy())
765 return (void)markOverdefined(&PN);
766
767 if (getValueState(&PN).isOverdefined())
768 return; // Quick exit
769
770 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
771 // and slow us down a lot. Just mark them overdefined.
772 if (PN.getNumIncomingValues() > 64)
773 return (void)markOverdefined(&PN);
774
775 // Look at all of the executable operands of the PHI node. If any of them
776 // are overdefined, the PHI becomes overdefined as well. If they are all
777 // constant, and they agree with each other, the PHI becomes the identical
778 // constant. If they are constant and don't agree, the PHI is overdefined.
779 // If there are no executable operands, the PHI remains unknown.
780 Constant *OperandVal = nullptr;
781 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
782 LatticeVal IV = getValueState(PN.getIncomingValue(i));
783 if (IV.isUnknown()) continue; // Doesn't influence PHI node.
784
785 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
786 continue;
787
788 if (IV.isOverdefined()) // PHI node becomes overdefined!
789 return (void)markOverdefined(&PN);
790
791 if (!OperandVal) { // Grab the first value.
792 OperandVal = IV.getConstant();
793 continue;
794 }
795
796 // There is already a reachable operand. If we conflict with it,
797 // then the PHI node becomes overdefined. If we agree with it, we
798 // can continue on.
799
800 // Check to see if there are two different constants merging, if so, the PHI
801 // node is overdefined.
802 if (IV.getConstant() != OperandVal)
803 return (void)markOverdefined(&PN);
804 }
805
806 // If we exited the loop, this means that the PHI node only has constant
807 // arguments that agree with each other(and OperandVal is the constant) or
808 // OperandVal is null because there are no defined incoming arguments. If
809 // this is the case, the PHI remains unknown.
810 if (OperandVal)
811 markConstant(&PN, OperandVal); // Acquire operand value
812}
813
814void SCCPSolver::visitReturnInst(ReturnInst &I) {
815 if (I.getNumOperands() == 0) return; // ret void
816
817 Function *F = I.getParent()->getParent();
818 Value *ResultOp = I.getOperand(0);
819
820 // If we are tracking the return value of this function, merge it in.
821 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
822 DenseMap<Function*, LatticeVal>::iterator TFRVI =
823 TrackedRetVals.find(F);
824 if (TFRVI != TrackedRetVals.end()) {
825 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
826 return;
827 }
828 }
829
830 // Handle functions that return multiple values.
831 if (!TrackedMultipleRetVals.empty()) {
832 if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
833 if (MRVFunctionsTracked.count(F))
834 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
835 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
836 getStructValueState(ResultOp, i));
837 }
838}
839
840void SCCPSolver::visitTerminator(Instruction &TI) {
841 SmallVector<bool, 16> SuccFeasible;
842 getFeasibleSuccessors(TI, SuccFeasible);
843
844 BasicBlock *BB = TI.getParent();
845
846 // Mark all feasible successors executable.
847 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
848 if (SuccFeasible[i])
849 markEdgeExecutable(BB, TI.getSuccessor(i));
850}
851
852void SCCPSolver::visitCastInst(CastInst &I) {
853 LatticeVal OpSt = getValueState(I.getOperand(0));
854 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
855 markOverdefined(&I);
856 else if (OpSt.isConstant()) {
857 // Fold the constant as we build.
858 Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpSt.getConstant(),
859 I.getType(), DL);
860 if (isa<UndefValue>(C))
861 return;
862 // Propagate constant value
863 markConstant(&I, C);
864 }
865}
866
867void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
868 // If this returns a struct, mark all elements over defined, we don't track
869 // structs in structs.
870 if (EVI.getType()->isStructTy())
871 return (void)markOverdefined(&EVI);
872
873 // If this is extracting from more than one level of struct, we don't know.
874 if (EVI.getNumIndices() != 1)
875 return (void)markOverdefined(&EVI);
876
877 Value *AggVal = EVI.getAggregateOperand();
878 if (AggVal->getType()->isStructTy()) {
879 unsigned i = *EVI.idx_begin();
880 LatticeVal EltVal = getStructValueState(AggVal, i);
881 mergeInValue(getValueState(&EVI), &EVI, EltVal);
882 } else {
883 // Otherwise, must be extracting from an array.
884 return (void)markOverdefined(&EVI);
885 }
886}
887
888void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
889 auto *STy = dyn_cast<StructType>(IVI.getType());
890 if (!STy)
891 return (void)markOverdefined(&IVI);
892
893 // If this has more than one index, we can't handle it, drive all results to
894 // undef.
895 if (IVI.getNumIndices() != 1)
896 return (void)markOverdefined(&IVI);
897
898 Value *Aggr = IVI.getAggregateOperand();
899 unsigned Idx = *IVI.idx_begin();
900
901 // Compute the result based on what we're inserting.
902 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
903 // This passes through all values that aren't the inserted element.
904 if (i != Idx) {
905 LatticeVal EltVal = getStructValueState(Aggr, i);
906 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
907 continue;
908 }
909
910 Value *Val = IVI.getInsertedValueOperand();
911 if (Val->getType()->isStructTy())
912 // We don't track structs in structs.
913 markOverdefined(getStructValueState(&IVI, i), &IVI);
914 else {
915 LatticeVal InVal = getValueState(Val);
916 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
917 }
918 }
919}
920
921void SCCPSolver::visitSelectInst(SelectInst &I) {
922 // If this select returns a struct, just mark the result overdefined.
923 // TODO: We could do a lot better than this if code actually uses this.
924 if (I.getType()->isStructTy())
925 return (void)markOverdefined(&I);
926
927 LatticeVal CondValue = getValueState(I.getCondition());
928 if (CondValue.isUnknown())
929 return;
930
931 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
932 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
933 mergeInValue(&I, getValueState(OpVal));
934 return;
935 }
936
937 // Otherwise, the condition is overdefined or a constant we can't evaluate.
938 // See if we can produce something better than overdefined based on the T/F
939 // value.
940 LatticeVal TVal = getValueState(I.getTrueValue());
941 LatticeVal FVal = getValueState(I.getFalseValue());
942
943 // select ?, C, C -> C.
944 if (TVal.isConstant() && FVal.isConstant() &&
945 TVal.getConstant() == FVal.getConstant())
946 return (void)markConstant(&I, FVal.getConstant());
947
948 if (TVal.isUnknown()) // select ?, undef, X -> X.
949 return (void)mergeInValue(&I, FVal);
950 if (FVal.isUnknown()) // select ?, X, undef -> X.
951 return (void)mergeInValue(&I, TVal);
952 markOverdefined(&I);
953}
954
955// Handle Binary Operators.
956void SCCPSolver::visitBinaryOperator(Instruction &I) {
957 LatticeVal V1State = getValueState(I.getOperand(0));
958 LatticeVal V2State = getValueState(I.getOperand(1));
959
960 LatticeVal &IV = ValueState[&I];
961 if (IV.isOverdefined()) return;
962
963 if (V1State.isConstant() && V2State.isConstant()) {
964 Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
965 V2State.getConstant());
966 // X op Y -> undef.
967 if (isa<UndefValue>(C))
968 return;
969 return (void)markConstant(IV, &I, C);
970 }
971
972 // If something is undef, wait for it to resolve.
973 if (!V1State.isOverdefined() && !V2State.isOverdefined())
974 return;
975
976 // Otherwise, one of our operands is overdefined. Try to produce something
977 // better than overdefined with some tricks.
978 // If this is 0 / Y, it doesn't matter that the second operand is
979 // overdefined, and we can replace it with zero.
980 if (I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv)
981 if (V1State.isConstant() && V1State.getConstant()->isNullValue())
982 return (void)markConstant(IV, &I, V1State.getConstant());
983
984 // If this is:
985 // -> AND/MUL with 0
986 // -> OR with -1
987 // it doesn't matter that the other operand is overdefined.
988 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Mul ||
989 I.getOpcode() == Instruction::Or) {
990 LatticeVal *NonOverdefVal = nullptr;
991 if (!V1State.isOverdefined())
992 NonOverdefVal = &V1State;
993 else if (!V2State.isOverdefined())
994 NonOverdefVal = &V2State;
995
996 if (NonOverdefVal) {
997 if (NonOverdefVal->isUnknown())
998 return;
999
1000 if (I.getOpcode() == Instruction::And ||
1001 I.getOpcode() == Instruction::Mul) {
1002 // X and 0 = 0
1003 // X * 0 = 0
1004 if (NonOverdefVal->getConstant()->isNullValue())
1005 return (void)markConstant(IV, &I, NonOverdefVal->getConstant());
1006 } else {
1007 // X or -1 = -1
1008 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
1009 if (CI->isMinusOne())
1010 return (void)markConstant(IV, &I, NonOverdefVal->getConstant());
1011 }
1012 }
1013 }
1014
1015 markOverdefined(&I);
1016}
1017
1018// Handle ICmpInst instruction.
1019void SCCPSolver::visitCmpInst(CmpInst &I) {
1020 // Do not cache this lookup, getValueState calls later in the function might
1021 // invalidate the reference.
1022 if (ValueState[&I].isOverdefined()) return;
1023
1024 Value *Op1 = I.getOperand(0);
1025 Value *Op2 = I.getOperand(1);
1026
1027 // For parameters, use ParamState which includes constant range info if
1028 // available.
1029 auto V1Param = ParamState.find(Op1);
1030 ValueLatticeElement V1State = (V1Param != ParamState.end())
1031 ? V1Param->second
1032 : getValueState(Op1).toValueLattice();
1033
1034 auto V2Param = ParamState.find(Op2);
1035 ValueLatticeElement V2State = V2Param != ParamState.end()
1036 ? V2Param->second
1037 : getValueState(Op2).toValueLattice();
1038
1039 Constant *C = V1State.getCompare(I.getPredicate(), I.getType(), V2State);
1040 if (C) {
1041 if (isa<UndefValue>(C))
1042 return;
1043 LatticeVal CV;
1044 CV.markConstant(C);
1045 mergeInValue(&I, CV);
1046 return;
1047 }
1048
1049 // If operands are still unknown, wait for it to resolve.
1050 if (!V1State.isOverdefined() && !V2State.isOverdefined() &&
1051 !ValueState[&I].isConstant())
1052 return;
1053
1054 markOverdefined(&I);
1055}
1056
1057// Handle getelementptr instructions. If all operands are constants then we
1058// can turn this into a getelementptr ConstantExpr.
1059void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1060 if (ValueState[&I].isOverdefined()) return;
1061
1062 SmallVector<Constant*, 8> Operands;
1063 Operands.reserve(I.getNumOperands());
1064
1065 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1066 LatticeVal State = getValueState(I.getOperand(i));
1067 if (State.isUnknown())
1068 return; // Operands are not resolved yet.
1069
1070 if (State.isOverdefined())
1071 return (void)markOverdefined(&I);
1072
1073 assert(State.isConstant() && "Unknown state!")((State.isConstant() && "Unknown state!") ? static_cast
<void> (0) : __assert_fail ("State.isConstant() && \"Unknown state!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 1073, __PRETTY_FUNCTION__))
;
1074 Operands.push_back(State.getConstant());
1075 }
1076
1077 Constant *Ptr = Operands[0];
1078 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
1079 Constant *C =
1080 ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1081 if (isa<UndefValue>(C))
1082 return;
1083 markConstant(&I, C);
1084}
1085
1086void SCCPSolver::visitStoreInst(StoreInst &SI) {
1087 // If this store is of a struct, ignore it.
1088 if (SI.getOperand(0)->getType()->isStructTy())
1089 return;
1090
1091 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1092 return;
1093
1094 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1095 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1096 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1097
1098 // Get the value we are storing into the global, then merge it.
1099 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
1100 if (I->second.isOverdefined())
1101 TrackedGlobals.erase(I); // No need to keep tracking this!
1102}
1103
1104// Handle load instructions. If the operand is a constant pointer to a constant
1105// global, we can replace the load with the loaded constant value!
1106void SCCPSolver::visitLoadInst(LoadInst &I) {
1107 // If this load is of a struct, just mark the result overdefined.
1108 if (I.getType()->isStructTy())
1109 return (void)markOverdefined(&I);
1110
1111 LatticeVal PtrVal = getValueState(I.getOperand(0));
1112 if (PtrVal.isUnknown()) return; // The pointer is not resolved yet!
1113
1114 LatticeVal &IV = ValueState[&I];
1115 if (IV.isOverdefined()) return;
1116
1117 if (!PtrVal.isConstant() || I.isVolatile())
1118 return (void)markOverdefined(IV, &I);
1119
1120 Constant *Ptr = PtrVal.getConstant();
1121
1122 // load null is undefined.
1123 if (isa<ConstantPointerNull>(Ptr)) {
1124 if (NullPointerIsDefined(I.getFunction(), I.getPointerAddressSpace()))
1125 return (void)markOverdefined(IV, &I);
1126 else
1127 return;
1128 }
1129
1130 // Transform load (constant global) into the value loaded.
1131 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1132 if (!TrackedGlobals.empty()) {
1133 // If we are tracking this global, merge in the known value for it.
1134 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1135 TrackedGlobals.find(GV);
1136 if (It != TrackedGlobals.end()) {
1137 mergeInValue(IV, &I, It->second);
1138 return;
1139 }
1140 }
1141 }
1142
1143 // Transform load from a constant into a constant if possible.
1144 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
1145 if (isa<UndefValue>(C))
1146 return;
1147 return (void)markConstant(IV, &I, C);
1148 }
1149
1150 // Otherwise we cannot say for certain what value this load will produce.
1151 // Bail out.
1152 markOverdefined(IV, &I);
1153}
1154
1155void SCCPSolver::visitCallSite(CallSite CS) {
1156 Function *F = CS.getCalledFunction();
1157 Instruction *I = CS.getInstruction();
1158
1159 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2
Taking true branch
1160 if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
3
Assuming the condition is true
4
Taking true branch
1161 if (ValueState[I].isOverdefined())
5
Taking false branch
1162 return;
1163
1164 auto *PI = getPredicateInfoFor(I);
1165 if (!PI)
6
Assuming 'PI' is non-null
7
Taking false branch
1166 return;
1167
1168 auto *PBranch = dyn_cast<PredicateBranch>(getPredicateInfoFor(I));
1169 if (!PBranch) {
8
Taking false branch
1170 mergeInValue(ValueState[I], I, getValueState(PI->OriginalOp));
1171 return;
1172 }
1173
1174 Value *CopyOf = I->getOperand(0);
9
Calling 'User::getOperand'
16
Returning from 'User::getOperand'
17
'CopyOf' initialized here
1175 Value *Cond = PBranch->Condition;
1176
1177 // Everything below relies on the condition being a comparison.
1178 auto *Cmp = dyn_cast<CmpInst>(Cond);
1179 if (!Cmp) {
18
Taking false branch
1180 mergeInValue(ValueState[I], I, getValueState(PI->OriginalOp));
1181 return;
1182 }
1183
1184 Value *CmpOp0 = Cmp->getOperand(0);
1185 Value *CmpOp1 = Cmp->getOperand(1);
1186 if (CopyOf != CmpOp0 && CopyOf != CmpOp1) {
19
Assuming pointer value is null
20
Assuming 'CopyOf' is equal to 'CmpOp0'
1187 mergeInValue(ValueState[I], I, getValueState(PI->OriginalOp));
1188 return;
1189 }
1190
1191 if (CmpOp0 != CopyOf)
21
Taking false branch
1192 std::swap(CmpOp0, CmpOp1);
1193
1194 LatticeVal OriginalVal = getValueState(CopyOf);
22
Passing null pointer value via 1st parameter 'V'
23
Calling 'SCCPSolver::getValueState'
1195 LatticeVal EqVal = getValueState(CmpOp1);
1196 LatticeVal &IV = ValueState[I];
1197 if (PBranch->TrueEdge && Cmp->getPredicate() == CmpInst::ICMP_EQ) {
1198 addAdditionalUser(CmpOp1, I);
1199 if (OriginalVal.isConstant())
1200 mergeInValue(IV, I, OriginalVal);
1201 else
1202 mergeInValue(IV, I, EqVal);
1203 return;
1204 }
1205 if (!PBranch->TrueEdge && Cmp->getPredicate() == CmpInst::ICMP_NE) {
1206 addAdditionalUser(CmpOp1, I);
1207 if (OriginalVal.isConstant())
1208 mergeInValue(IV, I, OriginalVal);
1209 else
1210 mergeInValue(IV, I, EqVal);
1211 return;
1212 }
1213
1214 return (void)mergeInValue(IV, I, getValueState(PBranch->OriginalOp));
1215 }
1216 }
1217
1218 // The common case is that we aren't tracking the callee, either because we
1219 // are not doing interprocedural analysis or the callee is indirect, or is
1220 // external. Handle these cases first.
1221 if (!F || F->isDeclaration()) {
1222CallOverdefined:
1223 // Void return and not tracking callee, just bail.
1224 if (I->getType()->isVoidTy()) return;
1225
1226 // Otherwise, if we have a single return value case, and if the function is
1227 // a declaration, maybe we can constant fold it.
1228 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
1229 canConstantFoldCallTo(CS, F)) {
1230 SmallVector<Constant*, 8> Operands;
1231 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1232 AI != E; ++AI) {
1233 LatticeVal State = getValueState(*AI);
1234
1235 if (State.isUnknown())
1236 return; // Operands are not resolved yet.
1237 if (State.isOverdefined())
1238 return (void)markOverdefined(I);
1239 assert(State.isConstant() && "Unknown state!")((State.isConstant() && "Unknown state!") ? static_cast
<void> (0) : __assert_fail ("State.isConstant() && \"Unknown state!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 1239, __PRETTY_FUNCTION__))
;
1240 Operands.push_back(State.getConstant());
1241 }
1242
1243 if (getValueState(I).isOverdefined())
1244 return;
1245
1246 // If we can constant fold this, mark the result of the call as a
1247 // constant.
1248 if (Constant *C = ConstantFoldCall(CS, F, Operands, TLI)) {
1249 // call -> undef.
1250 if (isa<UndefValue>(C))
1251 return;
1252 return (void)markConstant(I, C);
1253 }
1254 }
1255
1256 // Otherwise, we don't know anything about this call, mark it overdefined.
1257 return (void)markOverdefined(I);
1258 }
1259
1260 // If this is a local function that doesn't have its address taken, mark its
1261 // entry block executable and merge in the actual arguments to the call into
1262 // the formal arguments of the function.
1263 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1264 MarkBlockExecutable(&F->front());
1265
1266 // Propagate information from this call site into the callee.
1267 CallSite::arg_iterator CAI = CS.arg_begin();
1268 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1269 AI != E; ++AI, ++CAI) {
1270 // If this argument is byval, and if the function is not readonly, there
1271 // will be an implicit copy formed of the input aggregate.
1272 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1273 markOverdefined(&*AI);
1274 continue;
1275 }
1276
1277 if (auto *STy = dyn_cast<StructType>(AI->getType())) {
1278 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1279 LatticeVal CallArg = getStructValueState(*CAI, i);
1280 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
1281 }
1282 } else {
1283 // Most other parts of the Solver still only use the simpler value
1284 // lattice, so we propagate changes for parameters to both lattices.
1285 LatticeVal ConcreteArgument = getValueState(*CAI);
1286 bool ParamChanged =
1287 getParamState(&*AI).mergeIn(ConcreteArgument.toValueLattice(), DL);
1288 bool ValueChanged = mergeInValue(&*AI, ConcreteArgument);
1289 // Add argument to work list, if the state of a parameter changes but
1290 // ValueState does not change (because it is already overdefined there),
1291 // We have to take changes in ParamState into account, as it is used
1292 // when evaluating Cmp instructions.
1293 if (!ValueChanged && ParamChanged)
1294 pushToWorkList(ValueState[&*AI], &*AI);
1295 }
1296 }
1297 }
1298
1299 // If this is a single/zero retval case, see if we're tracking the function.
1300 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
1301 if (!MRVFunctionsTracked.count(F))
1302 goto CallOverdefined; // Not tracking this callee.
1303
1304 // If we are tracking this callee, propagate the result of the function
1305 // into this call site.
1306 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1307 mergeInValue(getStructValueState(I, i), I,
1308 TrackedMultipleRetVals[std::make_pair(F, i)]);
1309 } else {
1310 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1311 if (TFRVI == TrackedRetVals.end())
1312 goto CallOverdefined; // Not tracking this callee.
1313
1314 // If so, propagate the return value of the callee into this call result.
1315 mergeInValue(I, TFRVI->second);
1316 }
1317}
1318
1319void SCCPSolver::Solve() {
1320 // Process the work lists until they are empty!
1321 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1322 !OverdefinedInstWorkList.empty()) {
1323 // Process the overdefined instruction's work list first, which drives other
1324 // things to overdefined more quickly.
1325 while (!OverdefinedInstWorkList.empty()) {
1326 Value *I = OverdefinedInstWorkList.pop_back_val();
1327
1328 LLVM_DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "\nPopped off OI-WL: " << *
I << '\n'; } } while (false)
;
1329
1330 // "I" got into the work list because it either made the transition from
1331 // bottom to constant, or to overdefined.
1332 //
1333 // Anything on this worklist that is overdefined need not be visited
1334 // since all of its users will have already been marked as overdefined
1335 // Update all of the users of this instruction's value.
1336 //
1337 markUsersAsChanged(I);
1338 }
1339
1340 // Process the instruction work list.
1341 while (!InstWorkList.empty()) {
1342 Value *I = InstWorkList.pop_back_val();
1343
1344 LLVM_DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "\nPopped off I-WL: " << *I
<< '\n'; } } while (false)
;
1345
1346 // "I" got into the work list because it made the transition from undef to
1347 // constant.
1348 //
1349 // Anything on this worklist that is overdefined need not be visited
1350 // since all of its users will have already been marked as overdefined.
1351 // Update all of the users of this instruction's value.
1352 //
1353 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1354 markUsersAsChanged(I);
1355 }
1356
1357 // Process the basic block work list.
1358 while (!BBWorkList.empty()) {
1359 BasicBlock *BB = BBWorkList.back();
1360 BBWorkList.pop_back();
1361
1362 LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "\nPopped off BBWL: " << *BB
<< '\n'; } } while (false)
;
1363
1364 // Notify all instructions in this basic block that they are newly
1365 // executable.
1366 visit(BB);
1367 }
1368 }
1369}
1370
1371/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1372/// that branches on undef values cannot reach any of their successors.
1373/// However, this is not a safe assumption. After we solve dataflow, this
1374/// method should be use to handle this. If this returns true, the solver
1375/// should be rerun.
1376///
1377/// This method handles this by finding an unresolved branch and marking it one
1378/// of the edges from the block as being feasible, even though the condition
1379/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1380/// CFG and only slightly pessimizes the analysis results (by marking one,
1381/// potentially infeasible, edge feasible). This cannot usefully modify the
1382/// constraints on the condition of the branch, as that would impact other users
1383/// of the value.
1384///
1385/// This scan also checks for values that use undefs, whose results are actually
1386/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1387/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1388/// even if X isn't defined.
1389bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1390 for (BasicBlock &BB : F) {
1391 if (!BBExecutable.count(&BB))
1392 continue;
1393
1394 for (Instruction &I : BB) {
1395 // Look for instructions which produce undef values.
1396 if (I.getType()->isVoidTy()) continue;
1397
1398 if (auto *STy = dyn_cast<StructType>(I.getType())) {
1399 // Only a few things that can be structs matter for undef.
1400
1401 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1402 if (CallSite CS = CallSite(&I))
1403 if (Function *F = CS.getCalledFunction())
1404 if (MRVFunctionsTracked.count(F))
1405 continue;
1406
1407 // extractvalue and insertvalue don't need to be marked; they are
1408 // tracked as precisely as their operands.
1409 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1410 continue;
1411
1412 // Send the results of everything else to overdefined. We could be
1413 // more precise than this but it isn't worth bothering.
1414 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1415 LatticeVal &LV = getStructValueState(&I, i);
1416 if (LV.isUnknown())
1417 markOverdefined(LV, &I);
1418 }
1419 continue;
1420 }
1421
1422 LatticeVal &LV = getValueState(&I);
1423 if (!LV.isUnknown()) continue;
1424
1425 // extractvalue is safe; check here because the argument is a struct.
1426 if (isa<ExtractValueInst>(I))
1427 continue;
1428
1429 // Compute the operand LatticeVals, for convenience below.
1430 // Anything taking a struct is conservatively assumed to require
1431 // overdefined markings.
1432 if (I.getOperand(0)->getType()->isStructTy()) {
1433 markOverdefined(&I);
1434 return true;
1435 }
1436 LatticeVal Op0LV = getValueState(I.getOperand(0));
1437 LatticeVal Op1LV;
1438 if (I.getNumOperands() == 2) {
1439 if (I.getOperand(1)->getType()->isStructTy()) {
1440 markOverdefined(&I);
1441 return true;
1442 }
1443
1444 Op1LV = getValueState(I.getOperand(1));
1445 }
1446 // If this is an instructions whose result is defined even if the input is
1447 // not fully defined, propagate the information.
1448 Type *ITy = I.getType();
1449 switch (I.getOpcode()) {
1450 case Instruction::Add:
1451 case Instruction::Sub:
1452 case Instruction::Trunc:
1453 case Instruction::FPTrunc:
1454 case Instruction::BitCast:
1455 break; // Any undef -> undef
1456 case Instruction::FSub:
1457 case Instruction::FAdd:
1458 case Instruction::FMul:
1459 case Instruction::FDiv:
1460 case Instruction::FRem:
1461 // Floating-point binary operation: be conservative.
1462 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1463 markForcedConstant(&I, Constant::getNullValue(ITy));
1464 else
1465 markOverdefined(&I);
1466 return true;
1467 case Instruction::ZExt:
1468 case Instruction::SExt:
1469 case Instruction::FPToUI:
1470 case Instruction::FPToSI:
1471 case Instruction::FPExt:
1472 case Instruction::PtrToInt:
1473 case Instruction::IntToPtr:
1474 case Instruction::SIToFP:
1475 case Instruction::UIToFP:
1476 // undef -> 0; some outputs are impossible
1477 markForcedConstant(&I, Constant::getNullValue(ITy));
1478 return true;
1479 case Instruction::Mul:
1480 case Instruction::And:
1481 // Both operands undef -> undef
1482 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1483 break;
1484 // undef * X -> 0. X could be zero.
1485 // undef & X -> 0. X could be zero.
1486 markForcedConstant(&I, Constant::getNullValue(ITy));
1487 return true;
1488 case Instruction::Or:
1489 // Both operands undef -> undef
1490 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1491 break;
1492 // undef | X -> -1. X could be -1.
1493 markForcedConstant(&I, Constant::getAllOnesValue(ITy));
1494 return true;
1495 case Instruction::Xor:
1496 // undef ^ undef -> 0; strictly speaking, this is not strictly
1497 // necessary, but we try to be nice to people who expect this
1498 // behavior in simple cases
1499 if (Op0LV.isUnknown() && Op1LV.isUnknown()) {
1500 markForcedConstant(&I, Constant::getNullValue(ITy));
1501 return true;
1502 }
1503 // undef ^ X -> undef
1504 break;
1505 case Instruction::SDiv:
1506 case Instruction::UDiv:
1507 case Instruction::SRem:
1508 case Instruction::URem:
1509 // X / undef -> undef. No change.
1510 // X % undef -> undef. No change.
1511 if (Op1LV.isUnknown()) break;
1512
1513 // X / 0 -> undef. No change.
1514 // X % 0 -> undef. No change.
1515 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1516 break;
1517
1518 // undef / X -> 0. X could be maxint.
1519 // undef % X -> 0. X could be 1.
1520 markForcedConstant(&I, Constant::getNullValue(ITy));
1521 return true;
1522 case Instruction::AShr:
1523 // X >>a undef -> undef.
1524 if (Op1LV.isUnknown()) break;
1525
1526 // Shifting by the bitwidth or more is undefined.
1527 if (Op1LV.isConstant()) {
1528 if (auto *ShiftAmt = Op1LV.getConstantInt())
1529 if (ShiftAmt->getLimitedValue() >=
1530 ShiftAmt->getType()->getScalarSizeInBits())
1531 break;
1532 }
1533
1534 // undef >>a X -> 0
1535 markForcedConstant(&I, Constant::getNullValue(ITy));
1536 return true;
1537 case Instruction::LShr:
1538 case Instruction::Shl:
1539 // X << undef -> undef.
1540 // X >> undef -> undef.
1541 if (Op1LV.isUnknown()) break;
1542
1543 // Shifting by the bitwidth or more is undefined.
1544 if (Op1LV.isConstant()) {
1545 if (auto *ShiftAmt = Op1LV.getConstantInt())
1546 if (ShiftAmt->getLimitedValue() >=
1547 ShiftAmt->getType()->getScalarSizeInBits())
1548 break;
1549 }
1550
1551 // undef << X -> 0
1552 // undef >> X -> 0
1553 markForcedConstant(&I, Constant::getNullValue(ITy));
1554 return true;
1555 case Instruction::Select:
1556 Op1LV = getValueState(I.getOperand(1));
1557 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1558 if (Op0LV.isUnknown()) {
1559 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1560 Op1LV = getValueState(I.getOperand(2));
1561 } else if (Op1LV.isUnknown()) {
1562 // c ? undef : undef -> undef. No change.
1563 Op1LV = getValueState(I.getOperand(2));
1564 if (Op1LV.isUnknown())
1565 break;
1566 // Otherwise, c ? undef : x -> x.
1567 } else {
1568 // Leave Op1LV as Operand(1)'s LatticeValue.
1569 }
1570
1571 if (Op1LV.isConstant())
1572 markForcedConstant(&I, Op1LV.getConstant());
1573 else
1574 markOverdefined(&I);
1575 return true;
1576 case Instruction::Load:
1577 // A load here means one of two things: a load of undef from a global,
1578 // a load from an unknown pointer. Either way, having it return undef
1579 // is okay.
1580 break;
1581 case Instruction::ICmp:
1582 // X == undef -> undef. Other comparisons get more complicated.
1583 Op0LV = getValueState(I.getOperand(0));
1584 Op1LV = getValueState(I.getOperand(1));
1585
1586 if ((Op0LV.isUnknown() || Op1LV.isUnknown()) &&
1587 cast<ICmpInst>(&I)->isEquality())
1588 break;
1589 markOverdefined(&I);
1590 return true;
1591 case Instruction::Call:
1592 case Instruction::Invoke:
1593 // There are two reasons a call can have an undef result
1594 // 1. It could be tracked.
1595 // 2. It could be constant-foldable.
1596 // Because of the way we solve return values, tracked calls must
1597 // never be marked overdefined in ResolvedUndefsIn.
1598 if (Function *F = CallSite(&I).getCalledFunction())
1599 if (TrackedRetVals.count(F))
1600 break;
1601
1602 // If the call is constant-foldable, we mark it overdefined because
1603 // we do not know what return values are valid.
1604 markOverdefined(&I);
1605 return true;
1606 default:
1607 // If we don't know what should happen here, conservatively mark it
1608 // overdefined.
1609 markOverdefined(&I);
1610 return true;
1611 }
1612 }
1613
1614 // Check to see if we have a branch or switch on an undefined value. If so
1615 // we force the branch to go one way or the other to make the successor
1616 // values live. It doesn't really matter which way we force it.
1617 Instruction *TI = BB.getTerminator();
1618 if (auto *BI = dyn_cast<BranchInst>(TI)) {
1619 if (!BI->isConditional()) continue;
1620 if (!getValueState(BI->getCondition()).isUnknown())
1621 continue;
1622
1623 // If the input to SCCP is actually branch on undef, fix the undef to
1624 // false.
1625 if (isa<UndefValue>(BI->getCondition())) {
1626 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1627 markEdgeExecutable(&BB, TI->getSuccessor(1));
1628 return true;
1629 }
1630
1631 // Otherwise, it is a branch on a symbolic value which is currently
1632 // considered to be undef. Make sure some edge is executable, so a
1633 // branch on "undef" always flows somewhere.
1634 // FIXME: Distinguish between dead code and an LLVM "undef" value.
1635 BasicBlock *DefaultSuccessor = TI->getSuccessor(1);
1636 if (markEdgeExecutable(&BB, DefaultSuccessor))
1637 return true;
1638
1639 continue;
1640 }
1641
1642 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
1643 // Indirect branch with no successor ?. Its ok to assume it branches
1644 // to no target.
1645 if (IBR->getNumSuccessors() < 1)
1646 continue;
1647
1648 if (!getValueState(IBR->getAddress()).isUnknown())
1649 continue;
1650
1651 // If the input to SCCP is actually branch on undef, fix the undef to
1652 // the first successor of the indirect branch.
1653 if (isa<UndefValue>(IBR->getAddress())) {
1654 IBR->setAddress(BlockAddress::get(IBR->getSuccessor(0)));
1655 markEdgeExecutable(&BB, IBR->getSuccessor(0));
1656 return true;
1657 }
1658
1659 // Otherwise, it is a branch on a symbolic value which is currently
1660 // considered to be undef. Make sure some edge is executable, so a
1661 // branch on "undef" always flows somewhere.
1662 // FIXME: IndirectBr on "undef" doesn't actually need to go anywhere:
1663 // we can assume the branch has undefined behavior instead.
1664 BasicBlock *DefaultSuccessor = IBR->getSuccessor(0);
1665 if (markEdgeExecutable(&BB, DefaultSuccessor))
1666 return true;
1667
1668 continue;
1669 }
1670
1671 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1672 if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
1673 continue;
1674
1675 // If the input to SCCP is actually switch on undef, fix the undef to
1676 // the first constant.
1677 if (isa<UndefValue>(SI->getCondition())) {
1678 SI->setCondition(SI->case_begin()->getCaseValue());
1679 markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
1680 return true;
1681 }
1682
1683 // Otherwise, it is a branch on a symbolic value which is currently
1684 // considered to be undef. Make sure some edge is executable, so a
1685 // branch on "undef" always flows somewhere.
1686 // FIXME: Distinguish between dead code and an LLVM "undef" value.
1687 BasicBlock *DefaultSuccessor = SI->case_begin()->getCaseSuccessor();
1688 if (markEdgeExecutable(&BB, DefaultSuccessor))
1689 return true;
1690
1691 continue;
1692 }
1693 }
1694
1695 return false;
1696}
1697
1698static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
1699 Constant *Const = nullptr;
1700 if (V->getType()->isStructTy()) {
1701 std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
1702 if (llvm::any_of(IVs,
1703 [](const LatticeVal &LV) { return LV.isOverdefined(); }))
1704 return false;
1705 std::vector<Constant *> ConstVals;
1706 auto *ST = dyn_cast<StructType>(V->getType());
1707 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1708 LatticeVal V = IVs[i];
1709 ConstVals.push_back(V.isConstant()
1710 ? V.getConstant()
1711 : UndefValue::get(ST->getElementType(i)));
1712 }
1713 Const = ConstantStruct::get(ST, ConstVals);
1714 } else {
1715 const LatticeVal &IV = Solver.getLatticeValueFor(V);
1716 if (IV.isOverdefined())
1717 return false;
1718
1719 Const = IV.isConstant() ? IV.getConstant() : UndefValue::get(V->getType());
1720 }
1721 assert(Const && "Constant is nullptr here!")((Const && "Constant is nullptr here!") ? static_cast
<void> (0) : __assert_fail ("Const && \"Constant is nullptr here!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 1721, __PRETTY_FUNCTION__))
;
1722
1723 // Replacing `musttail` instructions with constant breaks `musttail` invariant
1724 // unless the call itself can be removed
1725 CallInst *CI = dyn_cast<CallInst>(V);
1726 if (CI && CI->isMustTailCall() && !CI->isSafeToRemove()) {
1727 CallSite CS(CI);
1728 Function *F = CS.getCalledFunction();
1729
1730 // Don't zap returns of the callee
1731 if (F)
1732 Solver.AddMustTailCallee(F);
1733
1734 LLVM_DEBUG(dbgs() << " Can\'t treat the result of musttail call : " << *CIdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << " Can\'t treat the result of musttail call : "
<< *CI << " as a constant\n"; } } while (false)
1735 << " as a constant\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << " Can\'t treat the result of musttail call : "
<< *CI << " as a constant\n"; } } while (false)
;
1736 return false;
1737 }
1738
1739 LLVM_DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << " Constant: " << *Const <<
" = " << *V << '\n'; } } while (false)
;
1740
1741 // Replaces all of the uses of a variable with uses of the constant.
1742 V->replaceAllUsesWith(Const);
1743 return true;
1744}
1745
1746// runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
1747// and return true if the function was modified.
1748static bool runSCCP(Function &F, const DataLayout &DL,
1749 const TargetLibraryInfo *TLI) {
1750 LLVM_DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "SCCP on function '" << F.getName
() << "'\n"; } } while (false)
;
1751 SCCPSolver Solver(DL, TLI);
1752
1753 // Mark the first block of the function as being executable.
1754 Solver.MarkBlockExecutable(&F.front());
1755
1756 // Mark all arguments to the function as being overdefined.
1757 for (Argument &AI : F.args())
1758 Solver.markOverdefined(&AI);
1759
1760 // Solve for constants.
1761 bool ResolvedUndefs = true;
1762 while (ResolvedUndefs) {
1763 Solver.Solve();
1764 LLVM_DEBUG(dbgs() << "RESOLVING UNDEFs\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "RESOLVING UNDEFs\n"; } } while (
false)
;
1765 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1766 }
1767
1768 bool MadeChanges = false;
1769
1770 // If we decided that there are basic blocks that are dead in this function,
1771 // delete their contents now. Note that we cannot actually delete the blocks,
1772 // as we cannot modify the CFG of the function.
1773
1774 for (BasicBlock &BB : F) {
1775 if (!Solver.isBlockExecutable(&BB)) {
1776 LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << BB)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << " BasicBlock Dead:" << BB;
} } while (false)
;
1777
1778 ++NumDeadBlocks;
1779 NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB);
1780
1781 MadeChanges = true;
1782 continue;
1783 }
1784
1785 // Iterate over all of the instructions in a function, replacing them with
1786 // constants if we have found them to be of constant values.
1787 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
1788 Instruction *Inst = &*BI++;
1789 if (Inst->getType()->isVoidTy() || Inst->isTerminator())
1790 continue;
1791
1792 if (tryToReplaceWithConstant(Solver, Inst)) {
1793 if (isInstructionTriviallyDead(Inst))
1794 Inst->eraseFromParent();
1795 // Hey, we just changed something!
1796 MadeChanges = true;
1797 ++NumInstRemoved;
1798 }
1799 }
1800 }
1801
1802 return MadeChanges;
1803}
1804
1805PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
1806 const DataLayout &DL = F.getParent()->getDataLayout();
1807 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1808 if (!runSCCP(F, DL, &TLI))
1809 return PreservedAnalyses::all();
1810
1811 auto PA = PreservedAnalyses();
1812 PA.preserve<GlobalsAA>();
1813 PA.preserveSet<CFGAnalyses>();
1814 return PA;
1815}
1816
1817namespace {
1818
1819//===--------------------------------------------------------------------===//
1820//
1821/// SCCP Class - This class uses the SCCPSolver to implement a per-function
1822/// Sparse Conditional Constant Propagator.
1823///
1824class SCCPLegacyPass : public FunctionPass {
1825public:
1826 // Pass identification, replacement for typeid
1827 static char ID;
1828
1829 SCCPLegacyPass() : FunctionPass(ID) {
1830 initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1831 }
1832
1833 void getAnalysisUsage(AnalysisUsage &AU) const override {
1834 AU.addRequired<TargetLibraryInfoWrapperPass>();
1835 AU.addPreserved<GlobalsAAWrapperPass>();
1836 AU.setPreservesCFG();
1837 }
1838
1839 // runOnFunction - Run the Sparse Conditional Constant Propagation
1840 // algorithm, and return true if the function was modified.
1841 bool runOnFunction(Function &F) override {
1842 if (skipFunction(F))
1843 return false;
1844 const DataLayout &DL = F.getParent()->getDataLayout();
1845 const TargetLibraryInfo *TLI =
1846 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1847 return runSCCP(F, DL, TLI);
1848 }
1849};
1850
1851} // end anonymous namespace
1852
1853char SCCPLegacyPass::ID = 0;
1854
1855INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",static void *initializeSCCPLegacyPassPassOnce(PassRegistry &
Registry) {
1856 "Sparse Conditional Constant Propagation", false, false)static void *initializeSCCPLegacyPassPassOnce(PassRegistry &
Registry) {
1857INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
1858INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",PassInfo *PI = new PassInfo( "Sparse Conditional Constant Propagation"
, "sccp", &SCCPLegacyPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<SCCPLegacyPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeSCCPLegacyPassPassFlag
; void llvm::initializeSCCPLegacyPassPass(PassRegistry &Registry
) { llvm::call_once(InitializeSCCPLegacyPassPassFlag, initializeSCCPLegacyPassPassOnce
, std::ref(Registry)); }
1859 "Sparse Conditional Constant Propagation", false, false)PassInfo *PI = new PassInfo( "Sparse Conditional Constant Propagation"
, "sccp", &SCCPLegacyPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<SCCPLegacyPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeSCCPLegacyPassPassFlag
; void llvm::initializeSCCPLegacyPassPass(PassRegistry &Registry
) { llvm::call_once(InitializeSCCPLegacyPassPassFlag, initializeSCCPLegacyPassPassOnce
, std::ref(Registry)); }
1860
1861// createSCCPPass - This is the public interface to this file.
1862FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
1863
1864static void findReturnsToZap(Function &F,
1865 SmallVector<ReturnInst *, 8> &ReturnsToZap,
1866 SCCPSolver &Solver) {
1867 // We can only do this if we know that nothing else can call the function.
1868 if (!Solver.isArgumentTrackedFunction(&F))
1869 return;
1870
1871 // There is a non-removable musttail call site of this function. Zapping
1872 // returns is not allowed.
1873 if (Solver.isMustTailCallee(&F)) {
1874 LLVM_DEBUG(dbgs() << "Can't zap returns of the function : " << F.getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "Can't zap returns of the function : "
<< F.getName() << " due to present musttail call of it\n"
; } } while (false)
1875 << " due to present musttail call of it\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "Can't zap returns of the function : "
<< F.getName() << " due to present musttail call of it\n"
; } } while (false)
;
1876 return;
1877 }
1878
1879 for (BasicBlock &BB : F) {
1880 if (CallInst *CI = BB.getTerminatingMustTailCall()) {
1881 LLVM_DEBUG(dbgs() << "Can't zap return of the block due to present "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "Can't zap return of the block due to present "
<< "musttail call : " << *CI << "\n"; } } while
(false)
1882 << "musttail call : " << *CI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "Can't zap return of the block due to present "
<< "musttail call : " << *CI << "\n"; } } while
(false)
;
1883 (void)CI;
1884 return;
1885 }
1886
1887 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1888 if (!isa<UndefValue>(RI->getOperand(0)))
1889 ReturnsToZap.push_back(RI);
1890 }
1891}
1892
1893// Update the condition for terminators that are branching on indeterminate
1894// values, forcing them to use a specific edge.
1895static void forceIndeterminateEdge(Instruction* I, SCCPSolver &Solver) {
1896 BasicBlock *Dest = nullptr;
1897 Constant *C = nullptr;
1898 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1899 if (!isa<ConstantInt>(SI->getCondition())) {
1900 // Indeterminate switch; use first case value.
1901 Dest = SI->case_begin()->getCaseSuccessor();
1902 C = SI->case_begin()->getCaseValue();
1903 }
1904 } else if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1905 if (!isa<ConstantInt>(BI->getCondition())) {
1906 // Indeterminate branch; use false.
1907 Dest = BI->getSuccessor(1);
1908 C = ConstantInt::getFalse(BI->getContext());
1909 }
1910 } else if (IndirectBrInst *IBR = dyn_cast<IndirectBrInst>(I)) {
1911 if (!isa<BlockAddress>(IBR->getAddress()->stripPointerCasts())) {
1912 // Indeterminate indirectbr; use successor 0.
1913 Dest = IBR->getSuccessor(0);
1914 C = BlockAddress::get(IBR->getSuccessor(0));
1915 }
1916 } else {
1917 llvm_unreachable("Unexpected terminator instruction")::llvm::llvm_unreachable_internal("Unexpected terminator instruction"
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 1917)
;
1918 }
1919 if (C) {
1920 assert(Solver.isEdgeFeasible(I->getParent(), Dest) &&((Solver.isEdgeFeasible(I->getParent(), Dest) && "Didn't find feasible edge?"
) ? static_cast<void> (0) : __assert_fail ("Solver.isEdgeFeasible(I->getParent(), Dest) && \"Didn't find feasible edge?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 1921, __PRETTY_FUNCTION__))
1921 "Didn't find feasible edge?")((Solver.isEdgeFeasible(I->getParent(), Dest) && "Didn't find feasible edge?"
) ? static_cast<void> (0) : __assert_fail ("Solver.isEdgeFeasible(I->getParent(), Dest) && \"Didn't find feasible edge?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 1921, __PRETTY_FUNCTION__))
;
1922 (void)Dest;
1923
1924 I->setOperand(0, C);
1925 }
1926}
1927
1928
1929bool llvm::runIPSCCP(
1930 Module &M, const DataLayout &DL, const TargetLibraryInfo *TLI,
1931 function_ref<std::unique_ptr<PredicateInfo>(Function &)> getPredicateInfo) {
1932 SCCPSolver Solver(DL, TLI);
1933
1934 // Loop over all functions, marking arguments to those with their addresses
1935 // taken or that are external as overdefined.
1936 for (Function &F : M) {
1937 if (F.isDeclaration())
1938 continue;
1939
1940 Solver.addPredInfo(F, getPredicateInfo(F));
1941 // Determine if we can track the function's return values. If so, add the
1942 // function to the solver's set of return-tracked functions.
1943 if (canTrackReturnsInterprocedurally(&F))
1944 Solver.AddTrackedFunction(&F);
1945
1946 // Determine if we can track the function's arguments. If so, add the
1947 // function to the solver's set of argument-tracked functions.
1948 if (canTrackArgumentsInterprocedurally(&F)) {
1949 Solver.AddArgumentTrackedFunction(&F);
1950 continue;
1951 }
1952
1953 // Assume the function is called.
1954 Solver.MarkBlockExecutable(&F.front());
1955
1956 // Assume nothing about the incoming arguments.
1957 for (Argument &AI : F.args())
1958 Solver.markOverdefined(&AI);
1959 }
1960
1961 // Determine if we can track any of the module's global variables. If so, add
1962 // the global variables we can track to the solver's set of tracked global
1963 // variables.
1964 for (GlobalVariable &G : M.globals()) {
1965 G.removeDeadConstantUsers();
1966 if (canTrackGlobalVariableInterprocedurally(&G))
1967 Solver.TrackValueOfGlobalVariable(&G);
1968 }
1969
1970 // Solve for constants.
1971 bool ResolvedUndefs = true;
1972 Solver.Solve();
1973 while (ResolvedUndefs) {
1974 LLVM_DEBUG(dbgs() << "RESOLVING UNDEFS\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "RESOLVING UNDEFS\n"; } } while (
false)
;
1975 ResolvedUndefs = false;
1976 for (Function &F : M)
1977 if (Solver.ResolvedUndefsIn(F)) {
1978 // We run Solve() after we resolved an undef in a function, because
1979 // we might deduce a fact that eliminates an undef in another function.
1980 Solver.Solve();
1981 ResolvedUndefs = true;
1982 }
1983 }
1984
1985 bool MadeChanges = false;
1986
1987 // Iterate over all of the instructions in the module, replacing them with
1988 // constants if we have found them to be of constant values.
1989 SmallVector<BasicBlock*, 512> BlocksToErase;
1990
1991 for (Function &F : M) {
1992 if (F.isDeclaration())
1993 continue;
1994
1995 if (Solver.isBlockExecutable(&F.front()))
1996 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;
1997 ++AI) {
1998 if (!AI->use_empty() && tryToReplaceWithConstant(Solver, &*AI)) {
1999 ++IPNumArgsElimed;
2000 continue;
2001 }
2002 }
2003
2004 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2005 if (!Solver.isBlockExecutable(&*BB)) {
2006 LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << *BB)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << " BasicBlock Dead:" << *BB
; } } while (false)
;
2007 ++NumDeadBlocks;
2008
2009 MadeChanges = true;
2010
2011 if (&*BB != &F.front())
2012 BlocksToErase.push_back(&*BB);
2013 continue;
2014 }
2015
2016 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
2017 Instruction *Inst = &*BI++;
2018 if (Inst->getType()->isVoidTy())
2019 continue;
2020 if (tryToReplaceWithConstant(Solver, Inst)) {
2021 if (Inst->isSafeToRemove())
2022 Inst->eraseFromParent();
2023 // Hey, we just changed something!
2024 MadeChanges = true;
2025 ++IPNumInstRemoved;
2026 }
2027 }
2028 }
2029
2030 // Change dead blocks to unreachable. We do it after replacing constants in
2031 // all executable blocks, because changeToUnreachable may remove PHI nodes
2032 // in executable blocks we found values for. The function's entry block is
2033 // not part of BlocksToErase, so we have to handle it separately.
2034 for (BasicBlock *BB : BlocksToErase)
2035 NumInstRemoved +=
2036 changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false);
2037 if (!Solver.isBlockExecutable(&F.front()))
2038 NumInstRemoved += changeToUnreachable(F.front().getFirstNonPHI(),
2039 /*UseLLVMTrap=*/false);
2040
2041 // Now that all instructions in the function are constant folded, erase dead
2042 // blocks, because we can now use ConstantFoldTerminator to get rid of
2043 // in-edges.
2044 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
2045 // If there are any PHI nodes in this successor, drop entries for BB now.
2046 BasicBlock *DeadBB = BlocksToErase[i];
2047 for (Value::user_iterator UI = DeadBB->user_begin(),
2048 UE = DeadBB->user_end();
2049 UI != UE;) {
2050 // Grab the user and then increment the iterator early, as the user
2051 // will be deleted. Step past all adjacent uses from the same user.
2052 auto *I = dyn_cast<Instruction>(*UI);
2053 do { ++UI; } while (UI != UE && *UI == I);
2054
2055 // Ignore blockaddress users; BasicBlock's dtor will handle them.
2056 if (!I) continue;
2057
2058 // If we have forced an edge for an indeterminate value, then force the
2059 // terminator to fold to that edge.
2060 forceIndeterminateEdge(I, Solver);
2061 bool Folded = ConstantFoldTerminator(I->getParent());
2062 assert(Folded &&((Folded && "Expect TermInst on constantint or blockaddress to be folded"
) ? static_cast<void> (0) : __assert_fail ("Folded && \"Expect TermInst on constantint or blockaddress to be folded\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 2063, __PRETTY_FUNCTION__))
2063 "Expect TermInst on constantint or blockaddress to be folded")((Folded && "Expect TermInst on constantint or blockaddress to be folded"
) ? static_cast<void> (0) : __assert_fail ("Folded && \"Expect TermInst on constantint or blockaddress to be folded\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 2063, __PRETTY_FUNCTION__))
;
2064 (void) Folded;
2065 }
2066
2067 // Finally, delete the basic block.
2068 F.getBasicBlockList().erase(DeadBB);
2069 }
2070 BlocksToErase.clear();
2071
2072 for (BasicBlock &BB : F) {
2073 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
2074 Instruction *Inst = &*BI++;
2075 if (Solver.getPredicateInfoFor(Inst)) {
2076 if (auto *II = dyn_cast<IntrinsicInst>(Inst)) {
2077 if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
2078 Value *Op = II->getOperand(0);
2079 Inst->replaceAllUsesWith(Op);
2080 Inst->eraseFromParent();
2081 }
2082 }
2083 }
2084 }
2085 }
2086 }
2087
2088 // If we inferred constant or undef return values for a function, we replaced
2089 // all call uses with the inferred value. This means we don't need to bother
2090 // actually returning anything from the function. Replace all return
2091 // instructions with return undef.
2092 //
2093 // Do this in two stages: first identify the functions we should process, then
2094 // actually zap their returns. This is important because we can only do this
2095 // if the address of the function isn't taken. In cases where a return is the
2096 // last use of a function, the order of processing functions would affect
2097 // whether other functions are optimizable.
2098 SmallVector<ReturnInst*, 8> ReturnsToZap;
2099
2100 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
2101 for (const auto &I : RV) {
2102 Function *F = I.first;
2103 if (I.second.isOverdefined() || F->getReturnType()->isVoidTy())
2104 continue;
2105 findReturnsToZap(*F, ReturnsToZap, Solver);
2106 }
2107
2108 for (const auto &F : Solver.getMRVFunctionsTracked()) {
2109 assert(F->getReturnType()->isStructTy() &&((F->getReturnType()->isStructTy() && "The return type should be a struct"
) ? static_cast<void> (0) : __assert_fail ("F->getReturnType()->isStructTy() && \"The return type should be a struct\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 2110, __PRETTY_FUNCTION__))
2110 "The return type should be a struct")((F->getReturnType()->isStructTy() && "The return type should be a struct"
) ? static_cast<void> (0) : __assert_fail ("F->getReturnType()->isStructTy() && \"The return type should be a struct\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 2110, __PRETTY_FUNCTION__))
;
2111 StructType *STy = cast<StructType>(F->getReturnType());
2112 if (Solver.isStructLatticeConstant(F, STy))
2113 findReturnsToZap(*F, ReturnsToZap, Solver);
2114 }
2115
2116 // Zap all returns which we've identified as zap to change.
2117 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
2118 Function *F = ReturnsToZap[i]->getParent()->getParent();
2119 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
2120 }
2121
2122 // If we inferred constant or undef values for globals variables, we can
2123 // delete the global and any stores that remain to it.
2124 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
2125 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
2126 E = TG.end(); I != E; ++I) {
2127 GlobalVariable *GV = I->first;
2128 assert(!I->second.isOverdefined() &&((!I->second.isOverdefined() && "Overdefined values should have been taken out of the map!"
) ? static_cast<void> (0) : __assert_fail ("!I->second.isOverdefined() && \"Overdefined values should have been taken out of the map!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 2129, __PRETTY_FUNCTION__))
2129 "Overdefined values should have been taken out of the map!")((!I->second.isOverdefined() && "Overdefined values should have been taken out of the map!"
) ? static_cast<void> (0) : __assert_fail ("!I->second.isOverdefined() && \"Overdefined values should have been taken out of the map!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Scalar/SCCP.cpp"
, 2129, __PRETTY_FUNCTION__))
;
2130 LLVM_DEBUG(dbgs() << "Found that GV '" << GV->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "Found that GV '" << GV->
getName() << "' is constant!\n"; } } while (false)
2131 << "' is constant!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sccp")) { dbgs() << "Found that GV '" << GV->
getName() << "' is constant!\n"; } } while (false)
;
2132 while (!GV->use_empty()) {
2133 StoreInst *SI = cast<StoreInst>(GV->user_back());
2134 SI->eraseFromParent();
2135 }
2136 M.getGlobalList().erase(GV);
2137 ++IPNumGlobalConst;
2138 }
2139
2140 return MadeChanges;
2141}

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h

1//===- llvm/User.h - User class definition ----------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class defines the interface that one who uses a Value must implement.
11// Each instance of the Value class keeps track of what User's have handles
12// to it.
13//
14// * Instructions are the largest class of Users.
15// * Constants may be users of other constants (think arrays and stuff)
16//
17//===----------------------------------------------------------------------===//
18
19#ifndef LLVM_IR_USER_H
20#define LLVM_IR_USER_H
21
22#include "llvm/ADT/iterator.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/IR/Use.h"
25#include "llvm/IR/Value.h"
26#include "llvm/Support/Casting.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/ErrorHandling.h"
29#include <cassert>
30#include <cstddef>
31#include <cstdint>
32#include <iterator>
33
34namespace llvm {
35
36template <typename T> class ArrayRef;
37template <typename T> class MutableArrayRef;
38
39/// Compile-time customization of User operands.
40///
41/// Customizes operand-related allocators and accessors.
42template <class>
43struct OperandTraits;
44
45class User : public Value {
46 template <unsigned>
47 friend struct HungoffOperandTraits;
48
49 LLVM_ATTRIBUTE_ALWAYS_INLINE__attribute__((always_inline)) inline static void *
50 allocateFixedOperandUser(size_t, unsigned, unsigned);
51
52protected:
53 /// Allocate a User with an operand pointer co-allocated.
54 ///
55 /// This is used for subclasses which need to allocate a variable number
56 /// of operands, ie, 'hung off uses'.
57 void *operator new(size_t Size);
58
59 /// Allocate a User with the operands co-allocated.
60 ///
61 /// This is used for subclasses which have a fixed number of operands.
62 void *operator new(size_t Size, unsigned Us);
63
64 /// Allocate a User with the operands co-allocated. If DescBytes is non-zero
65 /// then allocate an additional DescBytes bytes before the operands. These
66 /// bytes can be accessed by calling getDescriptor.
67 ///
68 /// DescBytes needs to be divisible by sizeof(void *). The allocated
69 /// descriptor, if any, is aligned to sizeof(void *) bytes.
70 ///
71 /// This is used for subclasses which have a fixed number of operands.
72 void *operator new(size_t Size, unsigned Us, unsigned DescBytes);
73
74 User(Type *ty, unsigned vty, Use *, unsigned NumOps)
75 : Value(ty, vty) {
76 assert(NumOps < (1u << NumUserOperandsBits) && "Too many operands")((NumOps < (1u << NumUserOperandsBits) && "Too many operands"
) ? static_cast<void> (0) : __assert_fail ("NumOps < (1u << NumUserOperandsBits) && \"Too many operands\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 76, __PRETTY_FUNCTION__))
;
77 NumUserOperands = NumOps;
78 // If we have hung off uses, then the operand list should initially be
79 // null.
80 assert((!HasHungOffUses || !getOperandList()) &&(((!HasHungOffUses || !getOperandList()) && "Error in initializing hung off uses for User"
) ? static_cast<void> (0) : __assert_fail ("(!HasHungOffUses || !getOperandList()) && \"Error in initializing hung off uses for User\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 81, __PRETTY_FUNCTION__))
81 "Error in initializing hung off uses for User")(((!HasHungOffUses || !getOperandList()) && "Error in initializing hung off uses for User"
) ? static_cast<void> (0) : __assert_fail ("(!HasHungOffUses || !getOperandList()) && \"Error in initializing hung off uses for User\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 81, __PRETTY_FUNCTION__))
;
82 }
83
84 /// Allocate the array of Uses, followed by a pointer
85 /// (with bottom bit set) to the User.
86 /// \param IsPhi identifies callers which are phi nodes and which need
87 /// N BasicBlock* allocated along with N
88 void allocHungoffUses(unsigned N, bool IsPhi = false);
89
90 /// Grow the number of hung off uses. Note that allocHungoffUses
91 /// should be called if there are no uses.
92 void growHungoffUses(unsigned N, bool IsPhi = false);
93
94protected:
95 ~User() = default; // Use deleteValue() to delete a generic Instruction.
96
97public:
98 User(const User &) = delete;
99
100 /// Free memory allocated for User and Use objects.
101 void operator delete(void *Usr);
102 /// Placement delete - required by std, called if the ctor throws.
103 void operator delete(void *Usr, unsigned) {
104 // Note: If a subclass manipulates the information which is required to calculate the
105 // Usr memory pointer, e.g. NumUserOperands, the operator delete of that subclass has
106 // to restore the changed information to the original value, since the dtor of that class
107 // is not called if the ctor fails.
108 User::operator delete(Usr);
109
110#ifndef LLVM_ENABLE_EXCEPTIONS
111 llvm_unreachable("Constructor throws?")::llvm::llvm_unreachable_internal("Constructor throws?", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 111)
;
112#endif
113 }
114 /// Placement delete - required by std, called if the ctor throws.
115 void operator delete(void *Usr, unsigned, bool) {
116 // Note: If a subclass manipulates the information which is required to calculate the
117 // Usr memory pointer, e.g. NumUserOperands, the operator delete of that subclass has
118 // to restore the changed information to the original value, since the dtor of that class
119 // is not called if the ctor fails.
120 User::operator delete(Usr);
121
122#ifndef LLVM_ENABLE_EXCEPTIONS
123 llvm_unreachable("Constructor throws?")::llvm::llvm_unreachable_internal("Constructor throws?", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 123)
;
124#endif
125 }
126
127protected:
128 template <int Idx, typename U> static Use &OpFrom(const U *that) {
129 return Idx < 0
130 ? OperandTraits<U>::op_end(const_cast<U*>(that))[Idx]
131 : OperandTraits<U>::op_begin(const_cast<U*>(that))[Idx];
132 }
133
134 template <int Idx> Use &Op() {
135 return OpFrom<Idx>(this);
136 }
137 template <int Idx> const Use &Op() const {
138 return OpFrom<Idx>(this);
139 }
140
141private:
142 const Use *getHungOffOperands() const {
143 return *(reinterpret_cast<const Use *const *>(this) - 1);
144 }
145
146 Use *&getHungOffOperands() { return *(reinterpret_cast<Use **>(this) - 1); }
147
148 const Use *getIntrusiveOperands() const {
149 return reinterpret_cast<const Use *>(this) - NumUserOperands;
150 }
151
152 Use *getIntrusiveOperands() {
153 return reinterpret_cast<Use *>(this) - NumUserOperands;
154 }
155
156 void setOperandList(Use *NewList) {
157 assert(HasHungOffUses &&((HasHungOffUses && "Setting operand list only required for hung off uses"
) ? static_cast<void> (0) : __assert_fail ("HasHungOffUses && \"Setting operand list only required for hung off uses\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 158, __PRETTY_FUNCTION__))
158 "Setting operand list only required for hung off uses")((HasHungOffUses && "Setting operand list only required for hung off uses"
) ? static_cast<void> (0) : __assert_fail ("HasHungOffUses && \"Setting operand list only required for hung off uses\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 158, __PRETTY_FUNCTION__))
;
159 getHungOffOperands() = NewList;
160 }
161
162public:
163 const Use *getOperandList() const {
164 return HasHungOffUses ? getHungOffOperands() : getIntrusiveOperands();
165 }
166 Use *getOperandList() {
167 return const_cast<Use *>(static_cast<const User *>(this)->getOperandList());
168 }
169
170 Value *getOperand(unsigned i) const {
171 assert(i < NumUserOperands && "getOperand() out of range!")((i < NumUserOperands && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i < NumUserOperands && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 171, __PRETTY_FUNCTION__))
;
10
Within the expansion of the macro 'assert':
a
Assuming the condition is true
172 return getOperandList()[i];
11
Assigning value
12
Calling 'Use::operator llvm::Value *'
14
Returning from 'Use::operator llvm::Value *'
15
Returning pointer
173 }
174
175 void setOperand(unsigned i, Value *Val) {
176 assert(i < NumUserOperands && "setOperand() out of range!")((i < NumUserOperands && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i < NumUserOperands && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 176, __PRETTY_FUNCTION__))
;
177 assert((!isa<Constant>((const Value*)this) ||(((!isa<Constant>((const Value*)this) || isa<GlobalValue
>((const Value*)this)) && "Cannot mutate a constant with setOperand!"
) ? static_cast<void> (0) : __assert_fail ("(!isa<Constant>((const Value*)this) || isa<GlobalValue>((const Value*)this)) && \"Cannot mutate a constant with setOperand!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 179, __PRETTY_FUNCTION__))
178 isa<GlobalValue>((const Value*)this)) &&(((!isa<Constant>((const Value*)this) || isa<GlobalValue
>((const Value*)this)) && "Cannot mutate a constant with setOperand!"
) ? static_cast<void> (0) : __assert_fail ("(!isa<Constant>((const Value*)this) || isa<GlobalValue>((const Value*)this)) && \"Cannot mutate a constant with setOperand!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 179, __PRETTY_FUNCTION__))
179 "Cannot mutate a constant with setOperand!")(((!isa<Constant>((const Value*)this) || isa<GlobalValue
>((const Value*)this)) && "Cannot mutate a constant with setOperand!"
) ? static_cast<void> (0) : __assert_fail ("(!isa<Constant>((const Value*)this) || isa<GlobalValue>((const Value*)this)) && \"Cannot mutate a constant with setOperand!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 179, __PRETTY_FUNCTION__))
;
180 getOperandList()[i] = Val;
181 }
182
183 const Use &getOperandUse(unsigned i) const {
184 assert(i < NumUserOperands && "getOperandUse() out of range!")((i < NumUserOperands && "getOperandUse() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i < NumUserOperands && \"getOperandUse() out of range!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 184, __PRETTY_FUNCTION__))
;
185 return getOperandList()[i];
186 }
187 Use &getOperandUse(unsigned i) {
188 assert(i < NumUserOperands && "getOperandUse() out of range!")((i < NumUserOperands && "getOperandUse() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i < NumUserOperands && \"getOperandUse() out of range!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 188, __PRETTY_FUNCTION__))
;
189 return getOperandList()[i];
190 }
191
192 unsigned getNumOperands() const { return NumUserOperands; }
193
194 /// Returns the descriptor co-allocated with this User instance.
195 ArrayRef<const uint8_t> getDescriptor() const;
196
197 /// Returns the descriptor co-allocated with this User instance.
198 MutableArrayRef<uint8_t> getDescriptor();
199
200 /// Set the number of operands on a GlobalVariable.
201 ///
202 /// GlobalVariable always allocates space for a single operands, but
203 /// doesn't always use it.
204 ///
205 /// FIXME: As that the number of operands is used to find the start of
206 /// the allocated memory in operator delete, we need to always think we have
207 /// 1 operand before delete.
208 void setGlobalVariableNumOperands(unsigned NumOps) {
209 assert(NumOps <= 1 && "GlobalVariable can only have 0 or 1 operands")((NumOps <= 1 && "GlobalVariable can only have 0 or 1 operands"
) ? static_cast<void> (0) : __assert_fail ("NumOps <= 1 && \"GlobalVariable can only have 0 or 1 operands\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 209, __PRETTY_FUNCTION__))
;
210 NumUserOperands = NumOps;
211 }
212
213 /// Subclasses with hung off uses need to manage the operand count
214 /// themselves. In these instances, the operand count isn't used to find the
215 /// OperandList, so there's no issue in having the operand count change.
216 void setNumHungOffUseOperands(unsigned NumOps) {
217 assert(HasHungOffUses && "Must have hung off uses to use this method")((HasHungOffUses && "Must have hung off uses to use this method"
) ? static_cast<void> (0) : __assert_fail ("HasHungOffUses && \"Must have hung off uses to use this method\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 217, __PRETTY_FUNCTION__))
;
218 assert(NumOps < (1u << NumUserOperandsBits) && "Too many operands")((NumOps < (1u << NumUserOperandsBits) && "Too many operands"
) ? static_cast<void> (0) : __assert_fail ("NumOps < (1u << NumUserOperandsBits) && \"Too many operands\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/User.h"
, 218, __PRETTY_FUNCTION__))
;
219 NumUserOperands = NumOps;
220 }
221
222 // ---------------------------------------------------------------------------
223 // Operand Iterator interface...
224 //
225 using op_iterator = Use*;
226 using const_op_iterator = const Use*;
227 using op_range = iterator_range<op_iterator>;
228 using const_op_range = iterator_range<const_op_iterator>;
229
230 op_iterator op_begin() { return getOperandList(); }
231 const_op_iterator op_begin() const { return getOperandList(); }
232 op_iterator op_end() {
233 return getOperandList() + NumUserOperands;
234 }
235 const_op_iterator op_end() const {
236 return getOperandList() + NumUserOperands;
237 }
238 op_range operands() {
239 return op_range(op_begin(), op_end());
240 }
241 const_op_range operands() const {
242 return const_op_range(op_begin(), op_end());
243 }
244
245 /// Iterator for directly iterating over the operand Values.
246 struct value_op_iterator
247 : iterator_adaptor_base<value_op_iterator, op_iterator,
248 std::random_access_iterator_tag, Value *,
249 ptrdiff_t, Value *, Value *> {
250 explicit value_op_iterator(Use *U = nullptr) : iterator_adaptor_base(U) {}
251
252 Value *operator*() const { return *I; }
253 Value *operator->() const { return operator*(); }
254 };
255
256 value_op_iterator value_op_begin() {
257 return value_op_iterator(op_begin());
258 }
259 value_op_iterator value_op_end() {
260 return value_op_iterator(op_end());
261 }
262 iterator_range<value_op_iterator> operand_values() {
263 return make_range(value_op_begin(), value_op_end());
264 }
265
266 struct const_value_op_iterator
267 : iterator_adaptor_base<const_value_op_iterator, const_op_iterator,
268 std::random_access_iterator_tag, const Value *,
269 ptrdiff_t, const Value *, const Value *> {
270 explicit const_value_op_iterator(const Use *U = nullptr) :
271 iterator_adaptor_base(U) {}
272
273 const Value *operator*() const { return *I; }
274 const Value *operator->() const { return operator*(); }
275 };
276
277 const_value_op_iterator value_op_begin() const {
278 return const_value_op_iterator(op_begin());
279 }
280 const_value_op_iterator value_op_end() const {
281 return const_value_op_iterator(op_end());
282 }
283 iterator_range<const_value_op_iterator> operand_values() const {
284 return make_range(value_op_begin(), value_op_end());
285 }
286
287 /// Drop all references to operands.
288 ///
289 /// This function is in charge of "letting go" of all objects that this User
290 /// refers to. This allows one to 'delete' a whole class at a time, even
291 /// though there may be circular references... First all references are
292 /// dropped, and all use counts go to zero. Then everything is deleted for
293 /// real. Note that no operations are valid on an object that has "dropped
294 /// all references", except operator delete.
295 void dropAllReferences() {
296 for (Use &U : operands())
297 U.set(nullptr);
298 }
299
300 /// Replace uses of one Value with another.
301 ///
302 /// Replaces all references to the "From" definition with references to the
303 /// "To" definition.
304 void replaceUsesOfWith(Value *From, Value *To);
305
306 // Methods for support type inquiry through isa, cast, and dyn_cast:
307 static bool classof(const Value *V) {
308 return isa<Instruction>(V) || isa<Constant>(V);
309 }
310};
311
312// Either Use objects, or a Use pointer can be prepended to User.
313static_assert(alignof(Use) >= alignof(User),
314 "Alignment is insufficient after objects prepended to User");
315static_assert(alignof(Use *) >= alignof(User),
316 "Alignment is insufficient after objects prepended to User");
317
318template<> struct simplify_type<User::op_iterator> {
319 using SimpleType = Value*;
320
321 static SimpleType getSimplifiedValue(User::op_iterator &Val) {
322 return Val->get();
323 }
324};
325template<> struct simplify_type<User::const_op_iterator> {
326 using SimpleType = /*const*/ Value*;
327
328 static SimpleType getSimplifiedValue(User::const_op_iterator &Val) {
329 return Val->get();
330 }
331};
332
333} // end namespace llvm
334
335#endif // LLVM_IR_USER_H

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/Use.h

1//===- llvm/Use.h - Definition of the Use class -----------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10///
11/// This defines the Use class. The Use class represents the operand of an
12/// instruction or some other User instance which refers to a Value. The Use
13/// class keeps the "use list" of the referenced value up to date.
14///
15/// Pointer tagging is used to efficiently find the User corresponding to a Use
16/// without having to store a User pointer in every Use. A User is preceded in
17/// memory by all the Uses corresponding to its operands, and the low bits of
18/// one of the fields (Prev) of the Use class are used to encode offsets to be
19/// able to find that User given a pointer to any Use. For details, see:
20///
21/// http://www.llvm.org/docs/ProgrammersManual.html#UserLayout
22///
23//===----------------------------------------------------------------------===//
24
25#ifndef LLVM_IR_USE_H
26#define LLVM_IR_USE_H
27
28#include "llvm-c/Types.h"
29#include "llvm/ADT/PointerIntPair.h"
30#include "llvm/Support/CBindingWrapping.h"
31#include "llvm/Support/Compiler.h"
32
33namespace llvm {
34
35template <typename> struct simplify_type;
36class User;
37class Value;
38
39/// A Use represents the edge between a Value definition and its users.
40///
41/// This is notionally a two-dimensional linked list. It supports traversing
42/// all of the uses for a particular value definition. It also supports jumping
43/// directly to the used value when we arrive from the User's operands, and
44/// jumping directly to the User when we arrive from the Value's uses.
45///
46/// The pointer to the used Value is explicit, and the pointer to the User is
47/// implicit. The implicit pointer is found via a waymarking algorithm
48/// described in the programmer's manual:
49///
50/// http://www.llvm.org/docs/ProgrammersManual.html#the-waymarking-algorithm
51///
52/// This is essentially the single most memory intensive object in LLVM because
53/// of the number of uses in the system. At the same time, the constant time
54/// operations it allows are essential to many optimizations having reasonable
55/// time complexity.
56class Use {
57public:
58 Use(const Use &U) = delete;
59
60 /// Provide a fast substitute to std::swap<Use>
61 /// that also works with less standard-compliant compilers
62 void swap(Use &RHS);
63
64 /// Pointer traits for the UserRef PointerIntPair. This ensures we always
65 /// use the LSB regardless of pointer alignment on different targets.
66 struct UserRefPointerTraits {
67 static inline void *getAsVoidPointer(User *P) { return P; }
68
69 static inline User *getFromVoidPointer(void *P) {
70 return (User *)P;
71 }
72
73 enum { NumLowBitsAvailable = 1 };
74 };
75
76 // A type for the word following an array of hung-off Uses in memory, which is
77 // a pointer back to their User with the bottom bit set.
78 using UserRef = PointerIntPair<User *, 1, unsigned, UserRefPointerTraits>;
79
80 /// Pointer traits for the Prev PointerIntPair. This ensures we always use
81 /// the two LSBs regardless of pointer alignment on different targets.
82 struct PrevPointerTraits {
83 static inline void *getAsVoidPointer(Use **P) { return P; }
84
85 static inline Use **getFromVoidPointer(void *P) {
86 return (Use **)P;
87 }
88
89 enum { NumLowBitsAvailable = 2 };
90 };
91
92private:
93 /// Destructor - Only for zap()
94 ~Use() {
95 if (Val)
96 removeFromList();
97 }
98
99 enum PrevPtrTag { zeroDigitTag, oneDigitTag, stopTag, fullStopTag };
100
101 /// Constructor
102 Use(PrevPtrTag tag) { Prev.setInt(tag); }
103
104public:
105 friend class Value;
106
107 operator Value *() const { return Val; }
13
Returning pointer
108 Value *get() const { return Val; }
109
110 /// Returns the User that contains this Use.
111 ///
112 /// For an instruction operand, for example, this will return the
113 /// instruction.
114 User *getUser() const LLVM_READONLY__attribute__((__pure__));
115
116 inline void set(Value *Val);
117
118 inline Value *operator=(Value *RHS);
119 inline const Use &operator=(const Use &RHS);
120
121 Value *operator->() { return Val; }
122 const Value *operator->() const { return Val; }
123
124 Use *getNext() const { return Next; }
125
126 /// Return the operand # of this use in its User.
127 unsigned getOperandNo() const;
128
129 /// Initializes the waymarking tags on an array of Uses.
130 ///
131 /// This sets up the array of Uses such that getUser() can find the User from
132 /// any of those Uses.
133 static Use *initTags(Use *Start, Use *Stop);
134
135 /// Destroys Use operands when the number of operands of
136 /// a User changes.
137 static void zap(Use *Start, const Use *Stop, bool del = false);
138
139private:
140 const Use *getImpliedUser() const LLVM_READONLY__attribute__((__pure__));
141
142 Value *Val = nullptr;
143 Use *Next;
144 PointerIntPair<Use **, 2, PrevPtrTag, PrevPointerTraits> Prev;
145
146 void setPrev(Use **NewPrev) { Prev.setPointer(NewPrev); }
147
148 void addToList(Use **List) {
149 Next = *List;
150 if (Next)
151 Next->setPrev(&Next);
152 setPrev(List);
153 *List = this;
154 }
155
156 void removeFromList() {
157 Use **StrippedPrev = Prev.getPointer();
158 *StrippedPrev = Next;
159 if (Next)
160 Next->setPrev(StrippedPrev);
161 }
162};
163
164/// Allow clients to treat uses just like values when using
165/// casting operators.
166template <> struct simplify_type<Use> {
167 using SimpleType = Value *;
168
169 static SimpleType getSimplifiedValue(Use &Val) { return Val.get(); }
170};
171template <> struct simplify_type<const Use> {
172 using SimpleType = /*const*/ Value *;
173
174 static SimpleType getSimplifiedValue(const Use &Val) { return Val.get(); }
175};
176
177// Create wrappers for C Binding types (see CBindingWrapping.h).
178DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Use, LLVMUseRef)inline Use *unwrap(LLVMUseRef P) { return reinterpret_cast<
Use*>(P); } inline LLVMUseRef wrap(const Use *P) { return reinterpret_cast
<LLVMUseRef>(const_cast<Use*>(P)); }
179
180} // end namespace llvm
181
182#endif // LLVM_IR_USE_H